【发布时间】:2021-02-11 16:00:28
【问题描述】:
我编写了一个父类,在其中定义了所有子类都应具有的一些函数(示例 __mul__、__truediv__ 等)。这些函数在执行后应该保持子类的类型。
这里有一些代码来解释我的意思:
class Magnet():
def __init__(self, length, strength):
self.length = length
self.strength = strength
return
def __mul__(self, other):
if np.isscalar(other):
return Magnet(self.length, self.strength * other)
else:
return NotImplemented
class Quadrupole(Magnet):
def __init__(self, length, strength, name):
super().__init__(length, strength)
self.name = name
return
现在如果我这样做:
Quad1 = Quadrupole(2, 10, 'Q1')
Quad2 = Quad1 * 2
那么 Quad1 属于“__main__.Quadrupole”类型,Quad2 属于“__main__.Magnet”类型。
我想知道如何做到这一点,以便保留子类型并且不会将其重新转换为父类型。一种解决方案是在子类中重新定义这些函数并更改
if np.isscalar(other):
return Magnet(self.length, self.strength * other)
到
if np.isscalar(other):
return Quadrupole(self.length, self.strength * other)
但进行继承的主要原因是不复制粘贴代码。可能类似于 super() 但向下,或者可能是类类型的占位符...
感谢您的帮助。
采用的解决方案
使用
return type(self)(self.length, self.strength * other)
有魅力。它会引发错误,因为我忘记在 Magnet.__init__() 中添加“名称”参数(我的原始代码确实如此,但在简化示例时搞砸了)。
我在这里也发现了同样的问题:Returning object of same subclass in __add__ operator
【问题讨论】:
标签: python-3.x inheritance types super