Method | Overloads | Call for |
---|---|---|
__init__ | 构造函数 | X=Class() |
__del__ | 析构函数 | 对象销毁 |
__add__ | + | X+Y,X+=Y |
__sub__ | - | X-Y |
__or__ | | | X|Y,X|=Y |
__repr__,__str__ | 打印转换 | print X, repr(X) |
__call__ | 调用函数 | X() |
__getattr__ | 点号运算 | X.undefine |
__setattr__ | 属性赋值语句 | X.any=value |
__getitem__ | 索引 | X[key], for if |
__setitem__ | 索引赋值语句 | X[key]=value, x[i:j]=v=sequence |
__len__ | 长度 | len(x) |
__cmp__ | 比较 | X==Y,X<Y |
__lt | 小于 | X<Y |
__eq__ | 等于 | X=Y |
_radd__ | +x | +Y |
__iadd__ | += | X+=Y |
__iter__ | 迭代 | For In |
__contains__ | 成员关系测试 | item in x |
__delitem__ | 索引和分片删除 | del x[key], del x[i:j] |
索引和分片:__getitem__和setitem__
如果在类中定义了的话,则对于实例的索引运算,会自动调用__getitem__。当实例x出现在x[i]这样的索引运算中时,python会调用这个实例继承的__getitem__方法。把x作为第一个参数传递,并且方括号内的索引值传给第二个参数。
>>>class Indexer:
... def __getitem__(self, index):
return index**2
>>>x = Indexer()
>>>x[2]
4
>>>for i in range(5)
... print(x[i], end=' ')
...
0,1,4,9,16