一、继承 我们先定义一个Bird()函数 >>> class Bird: ... def __init__(self): ... self.hungry=True ... def eat(self)
一、继承
我们先定义一个Bird()函数
>>> class Bird:
... def __init__(self):
... self.hungry=True
... def eat(self):
... if self.hungry:
... print 'Aaaaa...'
... self.hungry=False
... else:
... print 'no,thanks!'
...
...
运行结果:
>>> b=Bird()
>>> b.eat()
Aaaaa...
>>> b.eat()
no,thanks!
>>> b.eat()
no,thanks!
我们在定义一个SongBird()函数,让他继承Bird()函数的方法:
>>> class SongBird(Bird):
... def __init__(self):
... self.sound= 'love like wind'
... def sing(self):
... print self.sound
运行结果:
>>> sb=SongBird()
>>> sb.sing()
love like wind
>>> sb.eat()
Traceback (most recent call last):
File "<input>", line 1, in <module>
sb.eat()
File "<input>", line 5, in eat
if self.hungry:
AttributeError: SongBird instance has no attribute 'hungry'
>>>
SongBird是Bird的一个子类,它继承了eat方法,但是我们在调用eat方法时,出现了问题。
异常很清楚的说明了错误,SongBird没有hungry特性。原因是这样的,在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。为了达到预期的效果,SongBird的构造方法必须调用其超类Bird的构造方法来确保进行基本的初始化。有两种方法能够达到这个目的:调用超类构造方法的未绑定版本,或者使用super函数。
1、调用未绑定的超类构造方法:
>>> class SongBird(Bird):
...
... def __init__(self):
... Bird.__init__(self) //我们添加了这一句
... self.sound= 'love like wind'
... def sing(self):
... print self.sound
...
...
...
>>> sd=SongBird()
>>> sd.sing()
love like wind
>>> sd.eat()
Aaaaa...
>>> sd.eat()
no,thanks!
>>> sd.eat()
no,thanks!
>>>
在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上(这称为绑定方法)。但如果直接调用类的方法(比如Bird.__init__),那么就没有实例会被绑定。这样就可以自由的提供需要的self参数。这样的方法称未绑定(unbound)方法。通过将当前的实例作为self参数提供给未绑定方法,SongBird就能够使用其超类构造方法的所有实现,也就是说属性hungry能被设置。
2、使用super函数
>>> class SongBird(Bird):
... def __init__(self):
... super(SongBird.self).__init__() //我们直接使用super函数继承即可
... self.sound= 'love like wind'
... def sing(self):
... print self.sound
...
...
二、基本的序列和映射规则