内容简介:前面我们知道了在Python中如何继承。我们看下面的继承关系,Bird类有一个eat方法。BigBird继承了Bird,并且新增了sing方法。输出子类,
前面我们知道了在 Python 中如何继承。我们看下面的继承关系,Bird类有一个eat方法。BigBird继承了Bird,并且新增了sing方法。
class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print('开始吃,好好吃...')
self.hungry=False
else:
print('吃饱了,不要了...')
b= Bird()
b.eat();
b.eat()
输出
开始吃,好好吃... 吃饱了,不要了...
子类,
class BigBird(Bird):
def __init__(self):
self.sound='小燕子,穿花衣,年年春天来这里...'
def sing(self):
print(self.sound)
bg = BigBird()
bg.sing()
bg.eat()
调用sing方法输出
小燕子,穿花衣,年年春天来这里...
调用eat报异常如下:
Traceback (most recent call last):
File "D:/work/Python/ClassElement2.py", line 27, in <module>
bg.eat()
File "D:/work/Python/ClassElement2.py", line 9, in eat
if self.hungry:
AttributeError: 'BigBird' object has no attribute 'hungry'
因为BigBird中没有调用父类Bird中的构造函数,所以没有初始化父类的hungry的值。如果想要eat方法能正常执行,我们需要在BigBird的构造函数中调用父类的构造函数。
如下,
class BBigBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound='小燕子,穿花衣,年年春天来这里...'
def sing(self):
print(self.sound)
bg = BBigBird()
bg.sing()
bg.eat()
输出
小燕子,穿花衣,年年春天来这里... 开始吃,好好吃...
因为在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上。上面这种直接调用类的方法,比如Bird.__init__(self),其实没有实例绑定。这样的方法是未绑定的。
上面例子中,将当前BBigBird的实例作为self参数提供给未绑定的方法Bird.__init__,BBigBird就能够使用父类的构造函数,hungry会被赋值。
工程文件下载: https://download.csdn.net/download/yysyangyangyangshan/10797322
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Producing Masculinity
Michele White / Routledge / 2019-3 / $39.95
Thoughtful, witty, and illuminating, in this book Michele White explores the ways normative masculinity is associated with computers and the Internet and is a commonly enacted online gender practice. ......一起来看看 《Producing Masculinity》 这本书的介绍吧!