Python学习记录七---继承、多态和封装
1、创建类
创建文件 test7.py
#! /usr/bin/env python
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "hello, world! I am %s."% self.name
foo = Person()
foo.setName('yilia')
foo.getName()
foo.greet()
2、特性、函数、方法
私有变量: 只要在它的名字前面加上双下划线即可:
class Secretive:
def __inaccessible(self):
print "bet you can't see me"
def accessible(self):
print "this secret message is:"
self.__inaccessible() # 内部调用私有方法
s = Secretive()
s.accessible()
s.__inaccessible() #外部调用私有方法
3、类的命名空间
>>> class Counter:
... b = 0
... def init(self):
... self.b += 1
...
>>> num1 = Counter()
>>> num1.init()
>>> Counter.b
0
>>> num1.init()
>>> Counter.b
0
>>> num1.b
2
>>> num2 = Counter()
>>> num2.init()
>>> Counter.b
0
>>> num2.b
1
4、指定超类 将其它类名写在class语句后的圆括号内可以指定超类, 多个超类用“,”分隔
(1) 使用超类
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter):
def init(self):
self.blocked = ['SPAM']
(2) 查看一个类是否是另一个类的子类,使用issubclass
>>> isSubclass(SPAMFilter, Filter)
Ture
>>> isSubclass(Filter, SPAMFilter)
False
(3) 如果想要知道一个类的基类(们), 可以使用它的特殊属性 __bases__
>>> class Counter:
... b = 0
... def init(self):
... self.b += 1
...
>>> Counter.__bases__
()
>>> class AddCounter(Counter):
... def init(self):
... print "this is subClass"
...
>>> issubclass(AddCounter, Counter)
True
>>> AddCounter.__bases__
(<class __main__.Counter at 0x7fcd9b5db328>,)
>>>
5、接口和内省