问题描述
class Character(Entity):
def __init__(self, x, y, hp):
Entity.__init__(self, x, y)
self.hp = hp
self.items = []
Character
是父类Entity
的子类. Entity
类还具有__init__
函数.为什么需要同时编写两个__init__
函数?为什么不只为Character
类编写__init__()
,而这又会覆盖Entity
的__init__()
?
Character
is a child class of the parent class Entity
. Entity
class also has a __init__
function. Why is there a need to write both the __init__
functions? Why not only write the __init__()
for the Character
class, which would overwrite the __init__()
for Entity
?
推荐答案
这取决于Entity.__init__
中发生的事情!如果(并且仅当 )所有设置都设置为self.x
和self.y
,则可以执行以下操作:
It depends what happens in Entity.__init__
! If (and only if) all it does is set self.x
and self.y
, you could do:
class Character(Entity):
def __init__(self, x, y, hp):
self.x = x
self.y = y
self.hp = hp
self.items = []
但是这已经长了一行,并且如果除了为实例属性设置参数之外的其他任何内容在Entity.__init__
中完成(例如,在Character.__init__
中的self.items = []
), Character
可能无法正常工作.
But this is one line longer already, and if anything else other than setting arguments to instance attributes gets done in Entity.__init__
(like, for example, self.items = []
in Character.__init__
) your Character
may not work properly.
优良作法是调用超类的__init__
方法,以确保完成所有需要完成的工作.
It is good practice to call the super-class's __init__
method, to make sure that everything that needs to be done gets done.
您可以使用super
使代码更通用:
You can make your code more general using super
:
class Character(Entity):
def __init__(self, x, y, hp):
super(Character, self).__init__(x, y)
因此,如果您更改从__init__
继承的Character
仍然有效.
So that if you change what Character
inherits from your __init__
still works.
这篇关于嵌套的构造函数.为什么需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!