我正在为自己的解释器开发一个简单的类型系统。我正在写这样的东西:class Base(object): def __init__(self, content): self.__content = content @property def content(self): return self.__content @content.setter def content(self, value): self.__content = valueclass Number(Base): def __init__(self, content): super(Number, self).__init__(content) def __add__(self, other): return Number(self.content + other.content) ...and so onclass Float(Number): def __init__(self, content): super(Float, self).__init__(content)class Integer(Number): def __init__(self, content): super(Integer, self).__init__(content)我的问题是,如果我做这样的事情,显然:if __name__ == '__main__': f1 = Float(3.5) f2 = Float(2.3) f3 = f1 + f2 type(f3)我已经将f1和f2相加,它们是Float类型,但是我已经获得了f3,这是Number类型,但是我希望f3是Float类型。如何仅在我的Number超类中一次定义我的add运算符,以返回与f1和f2相同的类型?我有使用isinstance吗?有没有更清洁的方法可以做到这一点?
2 回答

三国纷争
TA贡献1804条经验 获得超7个赞
您可以使用__class__:
def __add__(self, other):
return self.__class__(self.content + other.content)
正如@Eric指出的那样,您可能想要做类似的事情
if self.__class__ == other.__class__:
<use __class__>
else:
<use Number>
以确保可预测的行为(如果类不匹配,则采取其他措施)。
__radd__ 在这里也值得覆盖:
__radd__ = __add__
这将使 Number(1) + Float(1) == Float(1) + Number(1) == Float(2)

守着一只汪
TA贡献1872条经验 获得超3个赞
我认为您想要{(1, 0): self.__class__, (0, 1): other.__class__}.get((issubclass(self.__class__, other.__class__), issubclass(other.__class__, self.__class__)), Number)
。如果我不必在评论中加上它,那将不太那么钝。
添加回答
举报
0/150
提交
取消