python's docs

1.2.3 magic method: 运算


1. 加减乘除

# coding:utf-8

from operator import add, sub, mul, div


class Cal(object):
    def __init__(self, x):
        super(Cal, self).__init__()
        self.x = x

    def __add__(self, y):
        self.x += y
        return self.x

    def __sub__(self, y):
        self.x -= y
        return self.x

    def __mul__(self, y):
        self.x *= y
        return self.x

    def __div__(self, y):
        self.x /= y
        return self.x


if __name__ == '__main__':
    base = Cal(3)

    # add
    x = base.x
    add(base, 1)
    print "{x} + 1 = {base}".format(x=x, base=base.x)

    # subtract
    x = base.x
    sub(base, 1)
    print "{x} - 1 = {base}".format(x=x, base=base.x)

    # multiply
    x = base.x
    mul(base, 2)
    print "{x} * 2 = {base}".format(x=x, base=base.x)

    # divide
    x = base.x
    div(base, 3)    
    print "{x} / 3 = {base}".format(x=x, base=base.x)