Python 中的 super 用法

来源:互联网 发布:淘宝买ps4哪家店好 编辑:程序博客网 时间:2024/06/08 18:35

super被用在:
当子类需要继承父类所有的属性和方法。可以理解为,用super可以继承父类的私有属性和方法。

例1:

>>> class A(object):...     def __init__(self):...             self.hungry = True...     def eat(self):...             if self.hungry:   #用到了私有的变量...                      print('i\'m hungry!!!')>>> class B(A):...     def sing(self):...             print(self.sound)>>> s = B()>>> s.eat()  #eat方法用到了类A的私有变量,无法访问Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 3, in eatAttributeError: 'B' object has no attribute 'hungry'

例2:

#增加super,就可以了。super(C,self) 等价于 A>>> class C(A):...     def __init__(self):...             super(C,self).__init__()...             self.sound = 'love me.mp3'...>>> s = C()>>> s.eat()i'm hungry!!!

例3:

>>> class A(object):...     def eat(self):...             print('i\'m hungry!!!')...>>> class B(A):...     def sing(self):...             print('self.sound')>>> s = B()>>> s.eat()    #由于eat并不是A类的私有方法,所以可以直接继承i'm hungry!!!
原创粉丝点击