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
问问题
2132 次
1 回答
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
于 2013-09-04T10:58:28.010 回答