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
Run Code Online (Sandbox Code Playgroud)
有一个错误__add__,应该是:
def __add__(self,other):
return MyInt(self.x + other.x)
Run Code Online (Sandbox Code Playgroud)
然后,您可以添加MyInt实例:
a = MyInt(1)
b = MyInt(1)
c = a + b
print type(c) # prints <class '__main__.MyInt'>
print c.x # prints 2
Run Code Online (Sandbox Code Playgroud)
注意,这a + 1不起作用,因为1它不是一种类型MyInt.如果您想支持它,您需要改进您的__add__方法并定义在不同类型的other参数的情况下如何表现.
| 归档时间: |
|
| 查看次数: |
1855 次 |
| 最近记录: |