[英]How to extend Python class init
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 init method so the that SubThing
has both a name
and a time
property. 我想扩展该类并添加到init方法,以便该SubThing
同时具有name
和time
属性。 How do I do it? 我该怎么做?
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. 任何帮助都是极好的。
You can just define __init__
in the subclass and call super
to 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 object
though, as super
won't work with old-style classes: 确保从object
获得基类子类,因为super
不适用于旧式类:
class Thing(object):
...
You should write another __init__
method in SubThing
and then call the constructor of the superclass to initialize its fields. 您应该在SubThing
编写另一个__init__
方法,然后调用超类的构造函数来初始化其字段。
This Q&A should provide you some more examples. 此问答应该为您提供更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.