嵌套的构造函数.为什么需要它? [英] nested constructor. Why is it required?

查看:67
本文介绍了嵌套的构造函数.为什么需要它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.xself.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.

这篇关于嵌套的构造函数.为什么需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆