如何扩展 Python 类 init

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12701206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:38:36  来源:igfitidea点击:

How to extend Python class init

pythonclassinheritanceinitialization

提问by MFB

I have created a base class:

我创建了一个基类:

class Thing():
    def __init__(self, name):
        self.name = name

I want to extend the class and add to the initmethod so the that SubThinghas both a nameand a timeproperty. How do I do it?

我想扩展该类并添加到init方法中,以便SubThing同时具有 aname和 atime属性。我该怎么做?

class SubThing(Thing):
    # something here to extend the init and add a "time" property

    def __repr__(self):
        return '<%s %s>' % (self.name, self.time)

Any help would be awesome.

任何帮助都是极好的。

采纳答案by Jesse

You can just define __init__in the subclass and call superto call the parents' __init__methods appropriately:

您可以__init__在子类中定义并调用super__init__适当地调用父类的方法:

class SubThing(Thing):
    def __init__(self, *args, **kwargs):
        super(SubThing, self).__init__(*args, **kwargs)
        self.time = datetime.now()

Make sure to have your base class subclass from objectthough, as superwon't work with old-style classes:

确保有你的基类子类object,因为super不适用于旧式类:

class Thing(object):
    ...

回答by mariosangiorgio

You should write another __init__method in SubThingand then call the constructor of the superclass to initialize its fields.

您应该在其中编写另一个__init__方法SubThing,然后调用超类的构造函数来初始化其字段。

This Q&A should provide you some more examples.

此问答应该为您提供更多示例。