pyhon中方法、属性、迭代器
构造方法:
构造方法代表着类似于以前例子中使用过的那种名为init的初始化方法
当一个对象被创建后,会立即调用构造方法
>>> class FooBar: def __init__(self): self.somevar=42 >>> f=FooBar() >>> f.somevar 42 >>> class fO SyntaxError: invalid syntax >>> class FooBar(): def __init__(self,value=42): self.somevar=value >>> f=FooBar('This is a constructor argument') >>> f.somevar 'This is a constructor argument'
重写一般方法和特殊的构造方法
>>> class Bird: def __init__(self): self.hungry=True def eat(self): if self.hungry: print 'Aaaah...' self.hungry=False else: print 'No,thanks!' >>> b=Bird() >>> b.eat() Aaaah... >>> b.eat() No,thanks! >>> class SongBird(Bird): def __init__(self): Bird.__init__(self) #调用超类的构造方法 self.sound='Squawk!' def sing(self): print self.sound >>> sb=SongBird() >>> sb.sing() Squawk! >>> sb.eat() Aaaah... >>> sb.eat() No,thanks!
super函数
super(SongBird,self)
详情请参考:http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html
>>> __metaclass__=type >>> class Bird: def __init__(self): self.hungry=True def eat(self): if self.hungry: print 'Aaaah...' self.hungry=False else: print 'No,thinks!' >>> class SongBird(Bird): def __init__(self): super(SongBird,self).__init__() self.sound='Squawk!' def sing(self): print self.sound >>> n=SongBird() >>> n.sing() Squawk! >>> n.eat() Aaaah... >>> n.eat() No,thinks!
属性
通过访问器定义的特性被称为属性
>>> 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 >>> r=Rectangle() >>> r.width=10 >>> r.height=5 >>> r.getSize() (10, 5) >>> r.setSize((150,100)) >>> r.width 150
property函数
>>> __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) >>> r=Rectangle() >>> r.width=10 >>> r.height=5 >>> r.size (10, 5) >>> r.size=150,100 >>> r.width 150
迭代器
迭代器就是具有next
>>> 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>1000: print f break 1597 >>> 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 生成器
任何包含yield语句的函数称为生成器。每次产生一个值(使用yield语句),函数就会被冻结,即函数停在那点等待被激活,函数被激活后从停止的那点开始执行
>>> nested=[[1,2],[3,4],[5]] >>> def flatten(nested): for sublist in nested: for element in sublist: yield element >>> for num in flatten(nested): print num 1 2 3 4 5