在 __add__ 运算符中返回相同子类的对象 [英] Returning object of same subclass in __add__ operator
问题描述
我正在为我自己的解释器开发一个简单的类型系统.我正在写这样的东西:
I am developing a simple type system for my own interpreter. I am writing something like this:
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 = value
class Number(Base):
def __init__(self, content):
super(Number, self).__init__(content)
def __add__(self, other):
return Number(self.content + other.content)
...and so on
class Float(Number):
def __init__(self, content):
super(Float, self).__init__(content)
class Integer(Number):
def __init__(self, content):
super(Integer, self).__init__(content)
我的问题显然是如果我这样做:
My problem is that obviously if I do something like this:
if __name__ == '__main__':
f1 = Float(3.5)
f2 = Float(2.3)
f3 = f1 + f2
type(f3)
我对f1和f2求和了,它们是Float类型,但是我得到了f3,它是Number类型,但是我希望f3是Float类型.我怎么能在我的 Number 超类中定义一次添加运算符,返回与 f1 和 f2 相同的类型?我必须使用 isinstance 吗?有没有更干净的方法来做到这一点?
I have summed f1 and f2, which are Float type, but I have obtained f3, which is Number type, but I would like f3 to be a Float type. How could I define my add operator just one time in my Number superclass returning a type which is the same of f1 and f2? Have I to use isinstance? Is there a cleaner way to do this?
谢谢!
推荐答案
你可以用 __class__
:
def __add__(self, other):
return self.__class__(self.content + other.content)
正如@Eric 指出的那样,您可能想要做类似
As, @Eric points out, you may want to do something like
if self.__class__ == other.__class__:
<use __class__>
else:
<use Number>
确保可预测的行为(或在类不匹配时采取其他一些行动).
to ensure predicable behaviour (or some other action if the classes don't match).
__radd__
也是值得在这里重写:
__radd__
is also worth overriding here:
__radd__ = __add__
这将使 Number(1) + Float(1) == Float(1) + Number(1) == Float(2)
这篇关于在 __add__ 运算符中返回相同子类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!