标签:style blog class code ext int
9.2 构造方法
python 中也属于自己的构造函数和析构函数,
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 fib = fibs() for i in fib: if i>1000: print i break
类在继承时不显示调用父类的构造方法时,父类构造方法中声明的元素不会被继承
class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Ohhh.haha!‘ self.hungry = False else: print ‘I\‘m full Thanks!‘ class SongBird(Bird): def __init__(self): self.sound = ‘Squawk!‘ def sing(self): print self.sound b = Bird() b.eat() b.eat() sb = SongBird() sb.sing() sb.eat()
class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Ohhh.haha!‘ self.hungry = False else: print ‘I\‘m full Thanks!‘ class SongBird(Bird): def __init__(self): self.sound = ‘Squawk!‘ Bird.__init__(self) def sing(self): print self.sound b = Bird() b.eat() b.eat() sb = SongBird() sb.sing() sb.eat()>>>
# -*- coding: cp936 -*- class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Ohhh.haha!‘ self.hungry = False else: print ‘I\‘m full Thanks!‘ @classmethod def say(self): print ‘Hello ,everybody!‘ #类中的方法都至少带个self参数 #这样声明的函数只用类对象才能调用 #只有@classmethod 或@staticmethod 可用类名调用,而不需要生成实例对象 class SongBird(Bird): def __init__(self): self.sound = ‘Squawk!‘ Bird.__init__(self) def sing(self): print self.sound b = Bird() b.eat() b.eat() b.say() Bird.say() sb = SongBird() sb.sing() sb.eat()
9.7递归生成器
# -*- coding: cp936 -*- def flatten(nested): try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested def flatten_new(nested): try: try:nested + ‘‘#列表不能加字符 except:pass else:raise TypeError for sublist in nested: for element in flatten_new(sublist): yield element except TypeError: yield nested test = [[[1],2],[3],[4,[5,[6,[7]]],8]] test_char = [‘foo‘,[‘bar‘,[‘join‘]],‘tu‘] print "old\n:",list(flatten(test)) print "new\n:",list(flatten_new(test)) print "new\n:",list(flatten_new(test_char)) print "old\n:",list(flatten(test_char))#死循环old
>>> def repeater(value): while True: new = (yield value) if new is not None:value = new >>> r = repeater(43) >>> r.next() 43 >>> r.next() 43 >>> r.send("hello!") ‘hello!‘ >>> r.next() ‘hello!‘ >>>
python 魔法方法,属性,迭代,布布扣,bubuko.com
标签:style blog class code ext int
原文地址:http://blog.csdn.net/nealgavin/article/details/25036857