【发布时间】:2016-04-21 23:53:01
【问题描述】:
我有一个向量类:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return '(%s,%s)' % (self.x, self.y)
def __add__(self, n):
if isinstance(n, (int, long, float)):
return Vector(self.x+n, self.y+n)
elif isinstance(n, Vector):
return Vector(self.x+n.x, self.y+n.y)
效果很好,即我可以写:
a = Vector(1,2)
print(a + 1) # prints (2,3)
但是如果操作顺序颠倒了,那就失败了:
a = Vector(1,2)
print(1 + a) # raises TypeError: unsupported operand type(s)
# for +: 'int' and 'instance'
我理解错误:将int 对象添加到Vector 对象是未定义的,因为我没有在int 类中定义它。有没有办法解决这个问题而不在int(或int的父级)类中定义它?
【问题讨论】:
-
您可能会发现这很有帮助:Special method names。另请参阅 Rafe Kettler 的 A Guide to Python's Magic Methods 和 Python’s magic methods
标签: python class object operator-overloading