为了账号安全,请及时绑定邮箱和手机立即绑定

什么是运算符重载 python

什么是运算符重载 python

心有法竹 2019-03-11 12:08:52
什么是运算符重载 python
查看完整描述

3 回答

?
临摹微笑

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()


 


查看完整回答
反对 回复 2019-03-17
?
偶然的你

TA贡献1841条经验 获得超3个赞

自定义类在+右边的时候,需要定义 __radd__(self, other) 方法。如果左侧的obj没有定义__add__,那么python会自动调用右侧obj的__radd__。
其它运算符也是这样的。都是前面加个r表示右侧,例如__rmul__

查看完整回答
反对 回复 2019-03-17
?
不负相思意

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]

查看完整回答
反对 回复 2019-03-17
  • 3 回答
  • 0 关注
  • 719 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信