2
我有两个类共享很多常见的东西,除了一个功能f(x)
。python类继承代码重用
class A(object):
def __init__(self):
// some stuff
def g(self):
// some other stuff
def f(self, x):
// many lines of computations
q = ...
y = ...
return y
class B(A):
def f(self, x):
// same many lines as in A
q = ...
y = ...
// a few extra lines
z = ... # z needs both y and q
return z
在这种情况下,我必须在B类中从头开始定义f(x)
吗?是否有一些技巧重新使用A.f(x)
中的代码?我能想到的
一种方法是使q
实例属性self.q
,然后执行以下操作
def f(self.x):
y = A.f(self, x)
// a few extra lines
z = ... # using y and self.q
return z
或许让A.f(x)
回报都q
和y
,然后调用A.f(self, x)
在B的的f(x)
定义。
这些方法是否是标准方法?有更好的东西吗?
'self.q'将是一个实例属性。 –
已更正。谢谢。 – nos
似乎是对我有效的方法。虽然'B'没有继承'g'函数,但它有关系吗? –