我有一个类层次结构,其中 class Base
中的 __init__
执行一些预初始化,然后调用方法 calculate
。 calculate
方法在 class Base
中定义,但预计会在派生类中重新定义。重新定义的 calculate
将使用一些仅在 class Derived
中可用的属性:
class Base:
def __init__(self, args):
# perform some pre-initialization
...
# now call method "calculate"
self.calculate()
class Derived(Base):
def __init__(self, args, additional_attr):
super().__init__(args)
# do some work and create new instance attributes
...
self.additional_attr = additional_attr
这不会起作用,因为 class Derived
中的 calculate
方法将在分配 self.additional_attr 之前被调用。
我不能将 super().__init__(args)
调用移动到 __init__
方法的末尾,因为它所做的一些工作必须在处理之前发生additional_attr
。
怎么办?
最佳答案
也许您不应该在构造函数中调用 calculate()
。如果您不能通过允许基构造函数首先完成来构造派生对象,那么恕我直言,您一定是做错了什么。一个明智的方法是将该调用移出构造函数,并可能创建一个工厂方法来自动进行该调用。如果您需要预先计算的实例,则使用该方法。
class Base(object):
def __init__(self, args):
# perform some initialization
pass
def calculate(self):
# do stuff
pass
@classmethod
def precalculated(cls, args):
# construct first
newBase = cls(args)
# now call method "calculate"
newBase.calculate()
return newBase
class Derived(Base):
def __init__(self, args, additional_attr):
super(Derived, self).__init__(args)
# do some work and create new instance attributes
self.additional_attr = additional_attr
@classmethod
def precalculated(cls, args, additional_attr): # also if you want
newDerived = cls(args, additional_attr)
newDerived.calculate()
return newDerived
newBase = Base('foo')
precalculatedBase = Base.precalculated('foo')
newDerived = Derived('foo', 'bar')
precalculatedDerived = Derived.precalculated('foo', 'bar')
关于python:在 __init__ 方法中过早调用 super().__init__ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5786441/