[英]Python inheritance: create child object in parent class
I have a parent class, with a method that returns a new object.我有一个父类,有一个返回新对象的方法。 I'd like that object to be of the same type as self (ie Parent if called within Parent class, Child if called in a Child instance).我希望该对象与 self 类型相同(即,如果在 Parent 类中调用,则为 Parent,如果在 Child 实例中调用则为 Child)。
class Parent(object):
def __init__(self,param):
self.param = param
def copy(self):
new_param = some_complicated_stuff(self.param)
return Parent(new_param)
class Child(Parent):
pass
C = Child(param)
D = C.copy()
Here D = C.copy()
will be of type Parent, regardless of the class C
.这里D = C.copy()
将是 Parent 类型,而不管C
类。 I would like to have copy return an instance of the same class as C
, while keeping the "some_complicated_stuff" part in the parent class in order to avoid code duplicate.我希望 copy 返回与C
相同类的实例,同时在父类中保留“some_complicated_stuff”部分以避免代码重复。
Context: Parent is an abstract group structure, "copy" returns subgroups (doing a series of algebraic operations), and I have many different Child classes that use this method.上下文:Parent 是一个抽象的组结构,“copy”返回子组(做一系列代数运算),我有很多不同的 Child 类使用这种方法。
You could use the fact that every instance has a pointer to its class under __class__
:您可以使用这样一个事实,即每个实例在__class__
下都有一个指向其类的指针:
class Parent(object):
def __init__(self,param):
self.param = param
def copy(self):
new_param = some_complicated_stuff(self.param)
return self.__class__(new_param)
This will be Parent
for the above class, but Child
in the derived class.这将是上述类的Parent
,但派生类中的Child
。
Instead of self.__class__
, you can also use type(self)
, as @Eli Korvigo has said in the comments , or as said here .除了self.__class__
,您还可以使用type(self)
,正如@Eli Korvigo 在评论中所说的那样,或者如here所说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.