如何pythonicly实现多态算术运算符?

Tyl*_*ler 4 python polymorphism type-conversion

我正在尝试创建一个类,允许我将同一个类的对象添加/相乘/分割,或者为该类的每个成员添加/乘以数字参数

所以我的班级是坐标(我知道那里有很棒的套餐可以做我想要的一切比我自己希望的更好,但现在我只是好奇).

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)
Run Code Online (Sandbox Code Playgroud)

这是我最初的尝试.我发现它有效,但前提是我先使用了数字参数

>>foo = GpsPoint(1,2,3)
>>print 5 + foo
6, 7, 8
>>print foo + 5
AttributeError: 'int' object has no attribute 'x'
Run Code Online (Sandbox Code Playgroud)

那么,做这个的pythonic方法是什么,有一种pythonic方式,这只是愚蠢吗?我看到使用的哲学问题是什么isinstance(),我知道我可以抛弃try except一块我只是好奇我应该怎么做.

Dan*_*l G 6

"Pythonic"方式是"请求宽恕而不是许可" - 也就是说,不是事先检查类型,而是尝试添加,如果失败,则捕获异常并处理它,如下所示:

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):
        try:
            return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)
        except AttributeError:
            return GpsPoint(self.x + other, self.y + other, self.z + other)
    def __radd__(self, other):
        try:
            return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)
        except AttributeError:
            return GpsPoint(self.x + other, self.y + other, self.z + other)
    def __str__(self):
        return "%d, %d, %d" % (self.x, self.y, self.z)
Run Code Online (Sandbox Code Playgroud)