python运算符重载

python运算符重载就是在解释器使用对象内置操作前,拦截该操作,使用自己写的重载方法。

重载方法:__init__为构造函数,__sub__为减法表达式

class Number:
def __init__(self, start):
    self.data = start

def __sub__(self, other):
    return Number(self.data - other)

>>>X = Number(5)
>>> Y = X - 2
>>> Y.data
3

其他重要的还有(省去前后的__):

del析构函数, add加法表达式, or, repr打印(print), str转化(str), call函数调用(不懂), getitem,setitem索引运算

len长度, bool布尔测试, cmp比较

def __setitem_(self, index, value):
    self.data[index] = value

def __getItem__(self, index):
    return self.data[index]

 

posted on 2016-12-13 17:50  LebronZhang  阅读(177)  评论(0编辑  收藏  举报

导航