python - 在 Python 中,如何避免在从其 __new__ : 中具有 super() 的类派生的类中调用 __init__ 两次

标签 python super derived-class

我是 python 新手。不知何故

__init__

对于派生自另一个类的类调用两次

super()

我的问题是如何避免这种情况,因为我在那里进行了非常昂贵的计算。

class A(object):
  def __new__(cls, *args, **kwargs):
    print("Class A: __new__")
    obj = super(A, cls).__new__(cls) # super is used here
    obj.__init__(*args, **kwargs)
    return obj
  def __init__(self, x):
    self.attrib = x+1

class B(A):
  def __init__(self, x):
    print("Class B: __init__")
    self.prop = 2*x # some expensive computation

a = A(10) # a test call

b = B(20) # Q: here, how to avoid calling __init__ twice in class B?

编辑: 谢谢你们的回答。我的真实代码是使用 scipy 库中内置的 arpack 对大型稀疏矩阵进行对角化。我正在调用在 arpack.py 中定义的类 SpLuInv(LinearOperator),其中类 LinearOperator 在 interface.py 中定义,两个文件都已附加:arpack.pyinterface.py .当我调用 SpLuInv() 时,它的 init 被调用了两次。根据您的回答,我认为我需要删除 LinearOperator() 的 new 中的 obj.init

感谢 Brendan Abel 的回答,感谢 Akshat Mahajan 和 Mike Graham 的评论。删除

obj.__init__

来自

__new__

LinearOperator()

解决了这个问题。 :)

最佳答案

您不应该在 __new__ 中手动调用 __init__。从 __new__ 返回的对象将自动调用 __init__

应该在您的所有类中调用父类(super class)__init__,即使它们仅继承自object .

这是唯一一次出现问题的情况是像单例 对象,它们通常从__new__ 返回一个已经__init__ 的对象。在这种情况下,您只需将类的实例存储为类属性,如果设置了属性,则直接从 __init__ 返回。

class A(object):
    def __new__(cls, *args, **kwargs):
        print("Class A: __new__")
        obj = super(A, cls).__new__(cls) # super is used here
        return obj

    def __init__(self, x):
        super(A, self).__init__()
        self.attrib = x+1

class B(A):
    def __init__(self, x):
        print("Class B: __init__")
        super(B, self).__init__(x)
        self.prop = 2*x # some expensive computation

关于python - 在 Python 中,如何避免在从其 __new__ : 中具有 super() 的类派生的类中调用 __init__ 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37403363/

相关文章:

python - 如何在 Python Fabric `env.hosts` 的函数中正确设置 `fabfile.py`?

python - QMenu 无法正确执行方法

Java设置实例的 super 实例

python - 为什么以及如何使用 Python 的 super(type1, type2)?

.net - 基类的实例如何保存派生类的实例?

c++ - 将多态类数据写入文件?

python - 如何使用 wand-py 和 imagemagick 运行此命令

python - 从 HTML 标签中移除某些属性

java - PowerMock:来自父类的 stub 方法

java - Java 中的参数化类型不匹配