Python继承和方法重写

2024-06-09 10:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个类,一个继承另一个。我们称它们为ParentChild。 从这些类创建的两个对象都应该使用函数funA,如下所示

funA():
  X = another_function()
  Y = # some value
  X.append(Y)
  # do other computations

对于这两个类,函数funA看起来几乎相同,只是函数another_function(),它以不同的方式计算Parent的列表{},而{}则不同。当然,我知道我可以重写子类中的函数funA,但是由于这个函数非常长,并且要执行多个操作,所以复制粘贴它会有点浪费。另一方面,我必须区分父类应该使用another_function()的一个版本,而子类应该使用another_function()的第二个版本。是否可以指出每个类应该使用another_function(我们称它们为another_function_v1another_function_v2)的哪个版本,或者是重写整个函数funA的唯一解决方案?在


Tags: 对象函数版本childvalueanotherfunctionsome
2条回答

我不知道你的另一个功能是什么。我想它们是正常函数,可以导入和使用

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

你的帖子不太清楚,但我认为funA是{}的一种方法。如果是,只需添加一些调用正确函数的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()

注意,如果funA是一个类方法,那么您也需要使another_method也成为一个类方法。。。在

相关问题 更多 >