python:在 __init__ 方法中过早调用 super().__init__ ?

标签 python class design-patterns

我有一个类层次结构,其中 class Base 中的 __init__ 执行一些预初始化,然后调用方法 calculatecalculate 方法在 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/

相关文章:

Python:比较不冗余的列表项

c++ - 如何从 OS X 终端编译带有多个类文件的 C++ 程序?

javascript - 如何在Javascript中访问其他对象的私有(private)方法(但它是相同的instanceof)

c++ - C++中通过引用传递类成员函数返回值

python - 如何找到列表中项目的索引,这些项目存在于另一个列表中?

python - 如何读取文件夹中的图像并存储其类别号和图像数据? Python

python - 我可以在排序列表时使 python 代码工作吗

php - MVC 面向对象技术 - 如何最小化查询并保持灵活性?

javascript - 如何在 javascript (nodejs) 中避免大量的 if-else

java - 对于派生数据库结构来说,什么是好的设计?