分类: 项目管理
2009-08-31 17:37:40
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
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)
静态方法和类方法:
class
MyClass:
@staticmethod
def
smeth():
print
'This is a static method'
@classmethod
def
cmeth(cls):
print
'This is a class method of', cls
__getattribute__
__getattr__(self,
name):
__setattr__(self,
name, value):
__delattr__(self,
name):
迭代器:
class
Fibs:
def
__init__(self):
self.a =
0
self.b =
1
def
next(self):
self.a,
self.b = self.b, self.a+self.b
return
self.a
def
__iter__(self):
return
self
>>>
nested = [[1, 2], [3, 4], [5]]
>>>
for num in flatten(nested):
print
num
...
1
2
3
4
5
or
>>>
list(flatten(nested))
[1, 2,
3, 4, 5]
本节余下部分待以后总结。