Pthon魔术方法(Magic Methods)-运算符重载

           Pthon魔术方法(Magic Methods)-运算符重载

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.Python运算符对应的魔术方法

1>.比较运算符

  <:
    对应__lt__

  <=:
    对应__le__

  ==:
    对应__eq__

  >:
    对应__gt__

  >=:
    对应__ge__

  !=:
    对应__ne__

2>.算数运算符

  +:
    对应__add__

  -:
    对应__sub__

  *:
    对应__mul__

  /:
    对应__truediv__

  %:
    对应__mod__

  //:
    对应__floordiv__

  **:
    对应__pow__

  divmod:
    对应__divmod__

3>.赋值运算符

  +=:
    对应__iadd__,一般会in-place就地来修改自身,如果没有定义该方法就会去找__add__方法。

  -=:
    对应__isub__,一般会in-place就地来修改自身,如果没有定义该方法就回去找__sub__方法,以下同理。

  *=:
    对应__imul__

  /=:
    对应__itruediv__

  %=:
    对应__imod__

  //=:
    对应__ifloordiv__

  **=:
    对应__ipow__

 

二.案例展示

 1 #!/usr/bin/env python
 2 #_*_conding:utf-8_*_
 3 #@author :yinzhengjie
 4 #blog:http://www.cnblogs.com/yinzhengjie
 5 
 6 """
 7     完成Point类设计,实现判断点相等的方法,并完成向量的加法。
 8 """
 9 
10 class Point:
11     def __init__(self,x,y):
12         self.x = x
13         self.y = y
14 
15     def __eq__(self, other):
16         return self.x == other.x and self.y == other.y
17 
18     def __add__(self, other):
19         return Point(self.x + other.x,self.y + other.y)
20 
21     def add(self,other):
22         return (self.x + other.x,self.y + other.y)
23 
24     def __str__(self):
25         return "<Point:{},{}>".format(self.x,self.y)
26 
27 p1 = Point(10,20)
28 p2 = Point(3,9)
29 
30 #使用普通方法调用
31 print(p1.add(p2))
32 
33 #使用运算符重载方法调用
34 print(p1 + p2)
35 print(p1 == p2)
36 
37 
38 #以上代码执行结果如下:
39 (13, 29)
40 <Point:13,29>
41 False

 

三.运算符重载应用场景

  往往是用咋子面向对象实现的类,需要大量的运算,而运算符是这种运算在数学上最常见的表达方式。

  例如,上例中的对"+"进行了运算符重载,实现了Point类的二元操作,重新定义为Point + Point。

  提供运算符重载,比直接提供方法要更加适合该领域内使用的习惯。

  int类,几乎实现了所有操作符,可以作为参考。

 

posted @ 2019-07-23 23:20  尹正杰  阅读(438)  评论(0编辑  收藏  举报