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 eat
AttributeError: '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!!!