#!usr/bin/env python
#coding=utf-8

from math import hypot

class Vector(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

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

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

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

    def __repr__(self):
        return "Vector({},{})".format(self.x, self.y)

    def __abs__(self):
        return hypot(self.x, self.y)

    def __bool__(self):
        return bool(self.x or self.y)

a = Vector(3, 4)
print(a*3)
print(a*4)
print(abs(a))
print(a-Vector(4,1))
print(a+Vector(4,1))
print(bool(a))
print(bool(Vector(0,0)))

python类中类似__XX__ 的方法,叫特殊方法。上面的__add__, __mul__等等都是运算符的特殊方法。
注意__bool__返回值为bool(self.x or self.y),这个bool很有必要,否则返回值是self.x 或者 self.y。因为对于x or y来说,如果bool(x)为真返回x,如果bool(x)不为真,bool(y)为真返回y,都不为真,返回y。

Special method names (operators excluded)

类别 方法名称
String/bytes representation __repr__ , __str__ , __format__ , __bytes__
Conversion to number __abs__ , __bool__ , __complex__ , __int__ , __float__ , __hash__ , __index__ ,
Emulating collections __len__ , __getitem__ , __setitem__ , __contains__ , __delitem__ ,
Iteration __iter__ , __reversed__ , __next__ ,
Emulating callable __call__
Context management __enter__ , __exit__ ,
Instance creation and destruction __init__ , __new__ , __del__ ,
Attribute management __getattr__ , __setattr__ , __delattr__ , __getattribute__ , __dir__ ,
Attribute descriptor __get__ , __set__ , __delete__
Class service __prepare__ , __instancecheck__ , __subclasscheck__

Special method names for operators

类别 方法名称
Unary numeric operators __neg__ (-), __pos__ (+), __abs__ (abs())
Rich comparison operators __lt__ (<), __le__ (<=) , __eq__ (==), __gt__ (>) , __ge__ (>=), __ne__ (!=)
Arithmetic operators __add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), __floordiv__ (//), __mod__ (%), __divmod__ (divmod()),__pow__ (**,pow()), __round__ (round()),
Reversed arithmetic operators __radd__ , __rsub__ , __rmul__ , __rtruediv__ , __rfloordiv__ , __rmod__ , __rdivmod__ , __rpow__ ,
Augmented assignment arithmetic operators __iadd__ , __isub__ , __imul__ , __itruediv__ , __ifloordiv__ , __imod__ , __ipow__ ,
Bitwise operators __invert__ (~), __lshift__ (<<), __rshift__ (>>), __and__ (&), __or__ (|), __xor__ (^)
Reversed bitwise operators __rlshift__ , __rrshift__ , __rand__ , __ror__ , __rxor__
Augmented assignment bitwise operators __ilshift__ , __irshift__ , __iand__ , __ior__ , __ixor__ ,