我是 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.py和 interface.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/