【问题标题】:Python - inheritance and method overridingPython - 继承和方法覆盖
【发布时间】:2017-05-29 15:02:43
【问题描述】:

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

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

对于这两个类,函数funA 看起来几乎相同,除了函数another_function(),它以不同的方式计算Parent 的列表X 和不同的Child。当然,我知道我可以在 Child 类中重写函数funA,但是由于这个函数很长,并且会进行多次操作,因此复制粘贴它会有点浪费。另一方面 - 我必须区分父类应该使用another_function() 的一个版本,而子类应该使用another_function() 的第二个版本。是否有可能指出每个类应该使用哪个版本的another_function(我们称它们为another_function_v1another_function_v2),或者如果覆盖整个函数funA是唯一的解决方案?

【问题讨论】:

  • 为什么不将another_function 的调用替换为function_calling_method 的调用,然后在子级中覆盖that
  • 您的funA 是静态方法还是类/实例方法?
  • @AzatIbrakov 这是一个类方法
  • @jonrsharpe 你能更准确地解释一下你的意思吗?
  • 那么X = cls.another_function()有什么问题呢?

标签: python class inheritance overriding


【解决方案1】:

您的帖子不太清楚,但我认为funAParent 的一种方法。如果是,只需添加一些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 如果funA 是一个类方法,你也会想让another_method 成为一个类方法...

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 1970-01-01
      • 2012-09-27
      • 2019-04-27
      • 2015-09-19
      • 2019-05-03
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      相关资源
      最近更新 更多