3 回答
![?](http://img1.sycdn.imooc.com/5458477300014deb02200220-100-100.jpg)
TA贡献1982条经验 获得超2个赞
example (Buffer support << , Fee support + / +=)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #!/usr/bin/env python # coding: utf-8
class Buffer(object): def __init__(self): self.buffer = []
def __lshift__(self, data): self.buffer.append(data) return self
def __str__(self): return repr(self.buffer)
class Fee(object): def __init__(self, qty=0, amount=0): self.qty = qty self.amount = amount
def __radd__(self, another): return self if not another else self + another
def __add__(self, another): return Fee( qty=self.qty + another.qty, amount=self.amount + another.amount )
def __repr__(self): return "%s(%s)" % ( self.__class__.__name__, ', '.join([ '%s=%r' % item for item in self.__dict__.items() ]) )
def tester(): buff = Buffer() buff << Fee(1, 23.5) << Fee(23, 1023.23) print sum(buff.buffer)
if __name__ == "__main__": tester() |
![?](http://img1.sycdn.imooc.com/545845b40001de9902200220-100-100.jpg)
TA贡献1841条经验 获得超3个赞
自定义类在+右边的时候,需要定义 __radd__(self, other) 方法。如果左侧的obj没有定义__add__,那么python会自动调用右侧obj的__radd__。
其它运算符也是这样的。都是前面加个r表示右侧,例如__rmul__
![?](http://img1.sycdn.imooc.com/5458622b000117dd02200220-100-100.jpg)
TA贡献1777条经验 获得超10个赞
class indexer:
def __getitem__(self, index): #iter override
return index ** 2
X = indexer()
X[2]
for i in range(5):
print X[i]
添加回答
举报