Python入门8_方法,属性,迭代器

来源:互联网 发布:淘宝 武士刀 编辑:程序博客网 时间:2024/06/03 19:20

1,继承机制:

上章讲到了class man(human): 这个表示类man继承human。下面介绍super( ),一个例子如下:

>>> class human:        def __init__(self):        self.gender = 'man'        def say(self):            if self.gender == 'man':                print 'I am a man'            else:                print 'I am a women'>>> class man(human):        def __init__(self):            self.name = 'Jack Ma'>>> f = man()>>> f.name'Jack Ma'>>> f.genderTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: man instance has no attribute 'gender'>>> f.say()Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: man instance has no attribute 'gender'

做了如下修改:

>>> class man(human):        def __init__(self):            super(man,self).__init__()            self.name = 'Jack Ma'>>> f = man()>>> f.say()TypeError: super() argument 1 must be type, not classobj# 这个python2会报错,python3没有问题

2,静态方法(可以直接通过类名调用的方法):

>>> class myclass{        @staticmethod        def mmm():            print "mmm"        @classmethod        def nnn():            print "nnn"}>>> myclass.mmm()#直接通过类名调用

3,迭代器:

#迭代器使用自己的方法:>>> class fibolacci:        def __init__(self):            self.a = 0            self.b = 1        def next(self):            self.a,self.b = self.b,self.a+self.b        def __iter__(self):            return self>>> fib = fibolacci()>>> for f in fib:        if(f>1000):            print f            break1597#for循环内部事实上就是先调用iter()把Iterable变成Iterator在进行循环迭代的>>> x = [1,3,4]>>> i = iter(x)>>> next(i)1>>> next(i)3>>> next(i)4#如果上面那个不好理解,那下面这个在网上找的可能更好理解:class Fabs(object):    def __init__(self,max):        self.max = max        self.n, self.a, self.b = 0, 0, 1  #特别指出:第0项是0,第1项是第一个1.整个数列从1开始    def __iter__(self):        return self    def next(self):        if self.n < self.max:            r = self.b            self.a, self.b = self.b, self.a + self.b            self.n = self.n + 1            return r        raise StopIteration()print Fabs(5)for key in Fabs(5):    print key
原创粉丝点击