class MyInt(object) :
# I'm trying to add two custom types (MyInt) together
# and have the sum be the same type. (MyInt)
# What am I doing wrong?
def __init__(self, x):
self.x = x
def __add__(self,other):
return self.x + other
a = MyInt(1)
b = MyInt(1)
print a + 1 # ----> 2
print type(a) # ----> "class '__main__.MyInt'
#c = a + b # this won't work
#print a + b # this won't work
答案 0 :(得分:5)
__add__
出错,应为:
def __add__(self,other):
return MyInt(self.x + other.x)
然后,您可以添加MyInt
个实例:
a = MyInt(1)
b = MyInt(1)
c = a + b
print type(c) # prints <class '__main__.MyInt'>
print c.x # prints 2
请注意,a + 1
不起作用,因为1
不是MyInt
的类型。如果您想支持它,则需要改进__add__
方法并定义在other
个不同类型参数的情况下如何操作。