Python中的构造函数是形如 def__init__(self),例如class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print'Ahhhh'
self.hungry=False
else:
print 'no,thx'
实例化类Bird对象b:
b=Bird()
b.eat()
b.eat()
Ahhhh
no,thx
假设现在Bird有一个子类Songbird(),继承了Bird()的方法和属性,class Songbird(Bird):
def __init__(self):
self.sound='ohlaohaloha'
def sing(self):
print self.sound
sb=Songbird()
sb.eat()
sb.eat()
调用后我们看到系统报错,因为Songbird的构造方法并没有任何关于hungry的代码。
AttributeError: Songbird instance has no attribute 'hungry'
尝试在子类Songbird的构造方法中增加超类中的方法eat(),也得到相同错误,因为eat()方法含有hungry变量。
那么如何在子类中调用超类的构造方法来初始化,使子类实例具有超类实例呢?提供两种方法:
1. 调用未绑定的超类构造