標籤:

Python 實例對象加法和字元串表示

有人提問,黃哥修改的代碼

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-8nnnntclass Point(object):nt """黃哥修改"""nnnt def __init__(self, x, y):nt self.x = xnt self.y = ynnnt def __add__(self, other):nnnt if isinstance(other, tuple):nt self.x += other[0]nt self.y += other[1]nt return selfnnnt elif isinstance(other, Point):nt self.x += other.xnt self.y += other.ynt return selfnnnt def __radd__(self, other):nt return self.__add__(other)nnnt def __str__(self):nt return "Point({0}, {1})".format(self.x, self.y)nnnt __repr__ = __str__nnntp1 = Point(1, 2)ntp2 = Point(3, 4)ntp3 = Point(2, 2)ntprint p1 + p2 + p3ntprint sum([p1 + p2 + (3, 5)], p3)ntprint str(p3)n

Python上海周末培訓班

216小時學會Python

推薦閱讀:

TAG:Python |