如何扩展 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
How to extend Python class init
提问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,然后调用超类的构造函数来初始化其字段。

