9.1 如果你使用的不是Python3
9.2 构造函数
>>> class FooBar:
def __init__(self):
self.somevar = 42
>>> f = FooBar()
>>> f.somevar
42
>>>
>>> class Foobar:
def __init__(self, value = 42):
self.somevar = value
>>> f = Foobar('This is a constructor argument')
>>> f.somevar
'This is a constructor argument'
>>>
9.2.1 重写普通方法和特殊的构造函数
9.2.2 调用未关联的超类构造函数
>>> class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk!'
9.2.3 使用函数super
super().__init__()
9.3 元素访问
9.3.1 基本的序列和映射协议
9.3.2 从list、dict和str派生
标准库中,模块collections提供了抽象和具体的基类,可以继承内置类型。
9.4 其他魔法方法
9.5 特性
9.5.1 函数property
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def set_size(self,size):
self.width,self.height = size
def get_size(self):
return self.width,self.height
size = property(get_size,set_size)
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5)
>>> r.size = 150,100
>>> r.width
150
>>>
9.5.2 静态方法和类方法
class MyClass:
@staticmethod
def smeth():
print('this is a static method')
@classmethod
def cmeth(cls):
print('this is a class method of', cls)
>>> MyClass.smeth()
this is a static method
>>> MyClass.cmeth()
this is a class method of <class '__main__.MyClass'>
>>>
9.5.3 __getattr__、__setattr__
等方法
9.6 迭代器
9.6.1 迭代器协议
迭代器协议
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
>>> fibs = Fibs()
>>> for f in fibs:
if f > 100:
break
else:
print(f," ")
1
1
2
3
5
8
13
21
34
55
89
9.6.2 从迭代器创建序列
9.7 生成器
9.7.1 创建生成器
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
>>> nested = [[1,2],[3,4],[5]]
>>> for num in flatten(nested):
print(num)
1
2
3
4
5
>>>
9.7.2 递归式
>>> def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
print('1: ',nested)
yield nested
9.7.3 通用生成器
>>> def simple_generator():
yield 1
>>> for i in simple_generator():
print(i)
1
>>>
9.7.4 生成器的方法