实例对象加法和字符串表示

有人提问
黄哥修改的代码

Python 类有特殊的方法__add__, __str__ 等。

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)

上面的方法被调用时,实现了相应的二元算术运算符。(+, -, , //, %, divmod(), pow(), *, <<, >>, &, ^, |)
实例说明:
表达式 x + y ,如果x的类有一个__add__方法,相当于x.__add__(y) 被调用。

类定义了__str__ 方法,当调用str()内置函数或Python 2的print 语句时,

这个方法就会被调用。

# coding:utf-8


class Point(object):
    """黄哥修改"""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):

        if isinstance(other, tuple):
            self.x += other[0]
            self.y += other[1]
            return self

        elif isinstance(other, Point):
            self.x += other.x
            self.y += other.y
            return self

    def __radd__(self, other):
        return self.__add__(other)

    def __str__(self):
        return "Point({0}, {1})".format(self.x, self.y)

    __repr__ = __str__

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = Point(2, 2)
print p1 + p2 + p3
print sum([p1 + p2 + (3, 5)], p3)
print str(p3)

Python上海周末培训班

216小时学会Python