【发布时间】:2010-03-02 23:36:12
【问题描述】:
我正在尝试创建一个类,该类允许我将同一类的对象添加/相乘/除法或将数字参数添加/相乘到类的每个成员
所以我的课程是针对坐标的(我知道有很多很棒的软件包可以比我自己希望做的更好,但现在我只是好奇)。
class GpsPoint(object):
"""A class for representing gps coordinates"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)
def __radd__(self, other):
return GpsPoint(self.x + other, self.y + other, self.z + other)
def __str__(self):
return "%d, %d, %d" % (self.x, self.y, self.z)
这是我最初的尝试。我发现它有效,但前提是我先使用数字参数
>>foo = GpsPoint(1,2,3)
>>print 5 + foo
6, 7, 8
>>print foo + 5
AttributeError: 'int' object has no attribute 'x'
那么,pythonic 的方法是什么,有没有 pythonic 的方法,这只是傻吗?我知道使用 isinstance() 的哲学问题是什么,我知道我可以在 try except 块中折腾我只是好奇我应该如何解决这个问题。
【问题讨论】:
标签: python polymorphism type-conversion