2017-05-29 147 views
0

我有两个类,一个从另一个继承。我们称它们为ParentChild。 无论从这些类创建应使用功能funA,它看起来像下面Python - 继承和方法覆盖

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

两个类,功能funA看起来几乎相同的对象,除了功能another_function(),它以不同的方式计算列表XParentChild不同。当然,我知道我可以覆盖Child类中的函数funA,但由于此函数非常长并且执行了多个操作,因此复制粘贴它会有点浪费。另一方面 - 我必须区分Parent类应使用another_function()的一个版本,Child类应使用another_function()的第二个版本。是否可能指向哪个版本的another_function(我们称之为another_function_v1another_function_v2)应该由每个类别使用或者唯一的解决方案是否覆盖整个功能funA

+1

为什么不为'function_calling_method'呼叫调用替换为'another_function',那么就重写*中的孩子,*? – jonrsharpe

+0

是你的'funA'静态或类/实例方法吗? –

+0

@AzatIbrakov它是一种方法 – Ziva

回答

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一类方法太...

1

我不知道你的another_functions来。我想他们是正常的功能,可以导入和使用

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