使用python添加两个自定义数据类型?

时间:2013-09-04 10:55:31

标签: python class types sum

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

1 个答案:

答案 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个不同类型参数的情况下如何操作。