[英]Python - inheritance and method overriding
I have two classes, one inheriting from the other. 我有两个类,一个从另一个继承。 Let's call them Parent
and Child
. 我们称它们为“ Parent
和Child
。 Both of the objects created from those classes should use function funA
, which looks like below 从这些类创建的两个对象都应使用funA
函数,如下所示
funA():
X = another_function()
Y = # some value
X.append(Y)
# do other computations
For both classes, function funA
looks almost the same, except function another_function()
, which computes in a different way the list X
for the Parent
and differently for the Child
. 对于这两个类,函数funA
看起来几乎相同,除了函数another_function()
,该函数以不同的方式计算Parent
的列表X
和Child
的列表X
Of course, I know that I can override function funA
in the Child class, but since this function is very long and does several operations, copy-pasting it would be a little bit a waste. 当然,我知道我可以在Child类中重写funA
函数,但是由于此函数很长并且需要执行多个操作,因此将其粘贴粘贴会有些浪费。 On the other hand - I have to distinguish that the Parent class should use one version of another_function()
and the Child class should use the second version of another_function()
. 另一方面-我必须区分父类应该使用another_function()
一个版本,而子类应该使用another_function()
的第二个版本。 Is is maybe possible to point which version of another_function
(let's call them another_function_v1
and another_function_v2
) should be used by each class or the only solution if to override the whole function funA
? 是否有可能指出每个类应该使用哪个版本的another_function
(我们将其称为another_function_v1
和another_function_v2
),还是覆盖整个功能funA
的唯一解决方案?
Your post is not quite clear but I assume funA
is a method of Parent
. 您的帖子不太清楚,但我认为funA
是Parent
的方法。 If yes, just add some another_method
method calling the right function: 如果是,只需添加一些调用正确函数的another_method
方法:
class Parent(object):
def another_method(self):
return another_function_v1()
def funA(self):
X = self.another_method()
Y = # some value
X.append(Y)
# do other computations
class Child(Parent):
def another_method(self):
return another_method_v2()
nb if funA
is a classmethod you will want to make another_method
a classmethod too... nb如果funA
是一个类方法,您也将要使another_method
成为一个类方法...
I don't know where your another_functions come. 我不知道您的another_functions在哪里。 I suppose they are normal functions, which can be imported and used 我想它们是正常功能,可以导入和使用
class Parent(object):
another_function = another_function_v1
def funA(self):
X = self.another_function()
Y = # some value
X.append(Y)
# do other computations
class Child(Parent):
another_function = another_function_v2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.