您的位置:首页 > 编程语言 > Python开发

python 中的重写一般方法和重写特殊的构造方法

2016-10-19 19:16 357 查看
在python中 有时需要进行重写,重写是继承机制中的一个重要部分, 可以重写一般方法也可以重写构造方法,构造方法是用来初始化新创建对象的状态。

class A :
def hello(self):
print('Hello,i am A.')
class B(A):
pass>>>a = A()
>>>b =B()

>>>a.hello()

Hello, i am A.

>>>b.hello()

Hello, i am A.

为什么会这样呢? 因为B类没有定义自己的hello方法,故当hello被调用时,原始信息就被打印出来了。

B类也可以重写这个hello方法。

class B(A):
def hello(self):
print('Hello,i am B.')>>>b = B()
>>>b.hello()

Hello,i am B.

以上的是重写一般方法!

——————————————————————————————————————————————————

如果特殊的构造方法被重写的话,将会导致原始基类的方法无法被调用。<pre name="code" class="python">class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaaah...')
self.hungry = False
else:
print('No,thanks!')

>>>b = Bird()

>>>b.eat()

Aaaah...

>>>b.eat()

No,thanks!

现在为子类SongBird .

class SongBird(Bird):
def __init__(self):
self.sound = 'Squawk!'
def sing(self):
print('self.sound')

>>>sb = SongBird()
>>>sb.sing()

Squawk!

>>>sb.eat()

报错,提示SongBird没有hungry特性。

如何解决这个问题呢?有两种方法:1、调用未绑定的基类构造方法  2、使用super函数

1调用未绑定的基类构造方法是怎么样呢? 让我们用实例来说明:

class SongBird(Bird):
def __init__(self):
Bird.__init__(self):
self.sound = 'Squawk!'
def sing(self):
print('self.sound')


只添加一行代码Bird.__init__(self).

>>>sb = SongBird()

>>>sb.sing()

Squawk!

>>>sb.eat()

Aaaah...

>>>sb.eat()

No.thanks!

2.使用super函数

class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaaah...')
self.hungry = False
else:
print('No,thanks!')
class SongBird(Bird):
def __init__(self):
Super(SongBird,self).__init__()
self.sound = 'Squawk!'
def sing(self):
print('self.sound')

>>>sb = SongBird()

>>>sb.sing()

Squawk!

>>>sb.eat()

Aaaah...

>>>sb.eat()

No.thanks!

=====================================END=========================================
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息