内容简介:前面我们知道了在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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- EasyMock:在java中模拟一个构造函数调用
- WPF 类型的构造函数执行符合指定的绑定约束的调用时引发了异常
- Java类 静态代码块、构造代码块、构造函数初始化顺序
- TS 的构造签名和构造函数类型是啥?傻傻分不清楚
- 只有你能 new 出来!.NET 隐藏构造函数的 n 种方法(Builder Pattern / 构造器模式)
- 构造函数、原型、原型链、继承
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Data Structures and Algorithms
Alfred V. Aho、Jeffrey D. Ullman、John E. Hopcroft / Addison Wesley / 1983-1-11 / USD 74.20
The authors' treatment of data structures in Data Structures and Algorithms is unified by an informal notion of "abstract data types," allowing readers to compare different implementations of the same......一起来看看 《Data Structures and Algorithms》 这本书的介绍吧!