我有一个由多个子类继承的基类。此基类有一个方法 calc_func(self),它在子类中使用统一命名的方法 func(self)。这可行,但如果代码变得更加复杂,这种“架构”将很难遵循。
# Base class
class base():
x = 12
def calc_func(self):
for i in range(1,4):
self.y += self.func()
# neither y nor func() are defined here so
# it is hard to know where they came from
# Child class 1
class child1(base):
y = 10
def __init__(self):
pass
def func(self): # method used in base class
self.x += self.y
print self.x
return self.x
# x was not defined here so it is
# hard to know where it came from
# Child class 2
class child2(base):
y = 15
def __init__(self):
pass
def func(self): # method used in base class
self.x *= self.y
print self.x
return self.x
# x was not defined here so it is
# hard to know where it came from
test1 = child1() # Create object
test1.calc_func() # Run method inherited from base class
test2 = child2() # Create another object
test2.calc_func() # Run method inherited from base class
想法是将通用代码抽象到基类中,但这似乎不是正确的做法。也许这可以通过使用引用其特定来源类的方法和属性的命名约定来更容易理解?也许完全不同的架构?任何建议将不胜感激。