【发布时间】:2016-09-21 01:32:39
【问题描述】:
我是 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),其中在 interface.py 中定义了类 LinearOperator,两个文件均已附加:arpack.py 和 interface.py。当我调用 SpLuInv() 时,它的 init 会被调用两次。根据您的回答,我认为我需要删除 LinearOperator() 的 new 中的 obj.init。
感谢 Brendan Abel 的回答以及 Akshat Mahajan 和 Mike Graham 的 cmets。删除
obj.__init__
来自
__new__
的
LinearOperator()
解决了这个问题。 :)
【问题讨论】:
-
你真的需要从
A继承吗?为什么不在B中定义你想要的具体方法呢? -
定义
__new__实际上总是一种次优方法。考虑分享你真实的代码。
标签: python super derived-class