小编Ahs*_*Zeb的帖子

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

我是python的新手。不知何故

__init__
Run Code Online (Sandbox Code Playgroud)

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

super()
Run Code Online (Sandbox Code Playgroud)

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

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?
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢两位的回答。我的真实代码是使用 scipy 库中内置的 arpack 对角化一个大型稀疏矩阵。我正在调用在 arpack.py 中定义的类 SpLuInv(LinearOperator),其中类 LinearOperator 在 …

python derived-class super

5
推荐指数
1
解决办法
1961
查看次数

标签 统计

derived-class ×1

python ×1

super ×1