4、property()函数
l property()函数只能用于new-style类,使用和属性相同的访问方式来替代访问方法(getter/setter方法)
class Rectangle(object):
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)
l 下面是使用size访问的例子:
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5)
>>> r.size = 150, 100
>>> r.width
150
l property()函数有4个可选参数,分别对应fget(getter方法)、fset(setter方法)、fdel(delete方法)和doc(docstring),如果只提供setter方法,可以使用keyword参数指定
5、静态方法和类方法
l 静态方法和类方法都是使用类名直接调用,区别是:静态方法不需要定义self参数,而类方法需要定义类似self的cls参数,在调用时会自动绑定到当前类
l 下面是使用“@修饰符”的形式来定义这些方法的例子:
class MyClass:
@staticmethod
def smeth():
print 'This is a static method'
@classmethod
def cmeth(cls):
print 'This is a class method of', cls
l 下面是调用这些方法的例子:
>>> MyClass.smeth()
This is a static method
>>> MyClass.cmeth()
This is a class method of __main__.MyClass
6、Iterator
l 对象可以具有Iterator功能,只要实现下面的方法:
Ø __iter__():返回Iterator(通常是对象本身),用于for循环
Ø next():用于返回下一个Iterator的值,如果没有值可以返回,需要抛StopIteration异常
l 下面是Fibonacci数列Iterator化的例子:
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.b
def __iter__(self):
return self
l 下面是调用的例子:输出大于1000的最小Fibonacci数值:
>>> fibs = Fibs()
>>> for f in fibs :
... if f > 1000 :
... print f
... break
...
1597
7、Generator
l Generator是一类Iterator,但定义成函数的语法,在函数中包含yield语句:每次调用yield语句时,停止执行后面的,返回yeild的值;等待唤醒后执行之后的语句
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
l 遍历Generator:
>>> nested = [[1, 2], [3, 4], [5]]
>>> for num in flatten(nested): print num,
...
1 2 3 4 5
l 转换成List:
>>> list(flatten(nested))
[1, 2, 3, 4, 5]
(1) 递归
l 上面的例子只有两层,下面是支持递归的版本:
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
l 下面是递归调用的例子:
>>> list(flatten([[[1],2],3,4,[5,[6,7]],8]))
[1, 2, 3, 4, 5, 6, 7, 8]
(2)处理string-like对象
l String本身就是Sequence,可以进行遍历,所以需要屏蔽掉这种情况,下面是改善的版本:
def flatten(nested):
try:
# Don't iterate over string-like objects:
try: nested + ''
except TypeError: pass
else: raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
l 下面是调用的例子:
>>> list(flatten(['foo', ['bar', ['baz']]]))
['foo', 'bar', 'baz']