##笔记
# 成员访问
# 基本的序列和映射规则
__len__(self)__
getitem__(self, key)__
setitem__(self, key, value)__
delitem__(self, key)
class X():
pass
##>>> len(X())
##Traceback (most recent call last):
## File "<stdin>", line 1, in <module>
##TypeError: object of type 'X' has no len()
class B():
def __init__(self):
pass
def __len__(self): # implement the len()
return 10
##>>> len(B())
##10
# 属性
class Rect():
def __init__(self):
self.width = 0
self.height = 0
def setSize(self, size): # size 为 tuple
self.width, self.height = size
def getSize(self):
return self.width, self,height
r = Rect()
r.setSize((100, 150))
r.getSize()
# property 函数
class Rect():
def __init__(self):
self.width = 0
self.height = 0
def setSize(self, size): # size 为 tuple
self.width, self.height = size
def getSize(self):
return self.width, self,height
size = property(getSize, setSize) # 此行
r = Rect()
r.width = 10
r.height = 5
r.size
>>>(10, 5)
>>>r.size = 150, 100
>>>r.width
150
# 这是一个很怪异的东西,虽然很怪异,但是在新式类中非常重要
# 静态方法和类成员方法
__metaclass__ = type
class MyClass():
def smeth():
print 'this is a static method'
smeth = staticmethod(smeth)
def cmeth(cls):
print 'this is a class method of .' ,cls
cmeth = classmethod(cmeth)
##>>> MyClass.smeth()
##this is a static method
##>>> MyClass().cmeth()
##this is a class method of . <class '__main__.MyClass'>
##>>> MyClass.cmeth()
##this is a class method of . <class '__main__.MyClass'>
##>>> MyClass.smeth()
##this is a static method
##>>>
# 采用修饰器的方式
__metaclass = type
class MyClass:
@staticmethod # 修饰器
def smeth():
print 'this is a static method'
@classmethod
def cmeth(cls):
print 'this is a class method of .' cls
# __getattr__ setattt__ 和 他的朋友们
__getattribute__(self, name)
__getattr__(self, name)
__setattr__(self, name, value)
__delattr__(self, name)
class Rect:
def __init__(self):
self.width = 0
self.height = 0
def __setattr__(self, name, value):
if name == 'size':
self.width, self.height = value
else:
self.__dict__[name] = value
def __getattr__(self, name):
if name == 'size':
return self.width, self.height
else:
raise AttributeError
# 迭代器 __iter__
# __iter__ 方法返回一个迭代器(iterator),所谓的迭代器就是具有 next() 方法的对象,这个方法在调用时不需要任何参数,在
# 调用next方法时,迭代器会返回它的下一个值。如果next方法被调用,但迭代器没有值可以返回,就会引发一个StopIteration异常
# 3.0中发生了一些变化
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
# 一个实现了 __iter__ 方法的对象是可以迭代的,一个实现了next方法的对象则是迭代器
fibs = Fibs()
for f in fibs:
if f>1000:
print(f)
break
# 内建函数iter可以从可迭代的对象中获得迭代器
##it = iter([1,2,3])
##>>>it.next()
##1
##>>>it.next()
##2
# 从迭代器得到序列
class TestIterator:
value = 0
def next(self):
self.value += 1
if self.value > 10 :raise StopIteration
return self.value
def __iter__(self):
return self
##>>> ti = TestIterator()
##>>> list(ti)
##[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
##>>>
# 生成器 yield
l = [[1,3,4], [5,7,9], [12,4,5]]
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
##>>> flatten(l)
##<generator object flatten at 0x01AD1148>
##>>> list(flatten(l))
##[1, 3, 4, 5, 7, 9, 12, 4, 5]
##>>>
# 循环生成器 列表推到
g = ((i+2)**2 for i in range(2, 27))
g.next()
16
# 递归生成器
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
# 改进版
def flatten(nested):
try:
try:nested + ''
except TypeError: pass
else: raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
l = [['foo'],['abc'], ['def']]
for x in flatten(l):
print x
# 生成器方法 send
# 使用send方法,只有在生成器挂起之后才有意义,也就是说yield函数第一次被执行以后
def repeater(value):
while True:
new = (yield value)
if new is not None : value = new
##>>> r = repeater(38)
##>>> r.next()
##38
##>>> r.send('Hello Python')
##'Hello Python'
##>>>
# throw close 方法 自行查阅
# 模拟生成器
def flatten(nested):
result = []
try:
try: nested + ''
except TypeError:pass
else: raise TypeError
for sublist in nested:
for element in flatten(sublist):
result.append(element)
except TypeError:
result.append(nested)
return result