类的特殊方法,迭代器,生成器
init(self,..)
如果一个类的构造方法被重写,需要调用超类的构造方法,否则对象可能不会被正确的初始化.
调用超类的两种方法:
1.调用未绑定的超类构造方法
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print "Aaaaah"
self.hungry = False
else:
print "No,Thanks"
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
...
直接调用类的方法(Bird.init()),那么没有实例会被绑定,这样可以自由提供self参数.将当前的实例作为self.参数提供给未绑定方法.
2.使用super函数
class SongBird(Bird):
def __init__(self):
super(Bird,self).__init__()
基本的序列和映射规则
1 len(self)
2 getitem(self, key)_: 类似于列表访问a[3]
3 __setitem(self, key, value): a[3] = 6
4 delitem(self,key): del a[3]
property函数
示例
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def setSize(self, size):
self.width,self.height = size
def getSize(self):
return self.width, self.height
size = property(getSize, setSize)
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10,5)
>>> r.size = 150,100
>>> r.width
150
使用方法: property(fget, fset, fdel, doc)
装饰器
class MyClass:
@staticmethod # 类的静态方法
def smeth():
print "This is a static method."
@classmethod
def cmeth(self):
print "This is a class method of ", cls
迭代器
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def next(self): # python3.0 中实现_next__()方法,而不是next,新的内建函数next用于访问这个方法
self.a, self.b = self.b, self.a + self.b
return self.a
def __iter__(self):
return self
>>> fibs = Fibs()
>>> for f in fibs:
if f > 1000:
print f
break
1597
一个实现了next方法的对象是迭代器,实现了__iter__方法的对象是可迭代的
>>> it = iter([1,2,3]) # iter内建函数从可迭代对象中得到迭代器
>>> it.next()
1
>>> it.next()
2
从迭代器得到序列
#将迭代器转换为列表
>>>print list(it)
[1,2,3]