特殊方法、属性、迭代器
构造函数
class FooBar:
def __init__(self):
self.somevar = 42
析构函数: __del__
继承父类的构造函数
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk!'
def sing(self):
print self.sound
另外一种方法:
__metaclass__ = type # super only works with new-style classes
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Aaaah...'
self.hungry =False
else:
print 'No,thanks!'
class SongBird(Bird):
def __init__(self):
super(SongBird,self).__init__()
self.sound = 'Squawk!'
def sing(self):
print self.sound
项目访问
__len__(self):
__nonzero__
__getitem__(self,key):
__setitem__(self,key, value):
__delitem__(self,key):
这块有待以后深入了解
属性
__metaclass__= type
classRectangle:
def__init__(self):
self.width= 0
self.height= 0
defsetSize(self, size):
self.width,self.height = size
defgetSize(self):
returnself.width, self.height
size =property(getSize, setSize)
静态方法和类方法:
classMyClass:
@staticmethod
defsmeth():
print'This is a static method'
@classmethod
defcmeth(cls):
print'This is a class method of', cls
__getattribute__
__getattr__(self,name):
__setattr__(self,name, value):
__delattr__(self,name):
迭代器:
classFibs:
def__init__(self):
self.a =0
self.b =1
defnext(self):
self.a,self.b = self.b, self.a+self.b
returnself.a
def__iter__(self):
returnself
>>>nested = [[1, 2], [3, 4], [5]]
>>>for num in flatten(nested):
printnum
...
1
2
3
4
5
or
>>>list(flatten(nested))
[1, 2,3, 4, 5]
本节余下部分待以后总结。