Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

38. Python 操作符重载

欢迎使用Python操作符重载教程。我们已经知道Python类,今天我们将学习面向对象python的另一个有趣特性。

Python运算符重载

Python运算符重载使我们能够像任何原始数据类型一样对Python对象使用数学、逻辑和位运算符。

例如,你可以很容易地用+运算符加上两个数字3和5,即3+5。结果是8。

但是如果你想添加两个圆(Circle类的对象)并使一个半径为两倍的圆呢?或者,如果您想添加两个笛卡尔网格点来生成具有相同“+”运算符的另一个点,该怎么办?Python运算符重载允许您执行与这些操作相同的操作。

Python运算符重载示例

现在,让我们看一个重载数学运算符的例子。


class GridPoint:  #Line: 1, Declaring a class
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  #Line: 4
  
    def __add__(self, other):  # Equivalent of + operator
        return GridPoint(self.x + other.x, self.y + other.y)
  
    def __str__(self):  #Line: 12, returns the attributes when the object is printed
        string = str(self.x)  
        string = string + ", " + str(self.y)  
        return string  #Line: 12
  
point1 = GridPoint(3, 5)  #Line: 14 Creating a grid point
point2 = GridPoint(-1, 4)  #Line: 15, Creating another point
point3 = point1 + point2  #Line: 16, Add two points using __add__() method
print(point3)  #Line: 17, Print the attributes using __str__() method

第1到4行表示类的声明GridPoint and definition of constructor method. Let’s have a look at lines 6 and 7.


    def __add__(self, other):  # Equivalent of + operator
        return GridPoint(self.x + other.x, self.y + other.y)

当我们使用“+”运算符作为数学加法运算时__add__() method is implicitly called.

因此,如果要添加类GridPoint的两个对象,则必须重新定义此方法。因此,这里我们需要创建另一个GridPoint类的实例,它的x值是围绕“+”运算符的两个网格点实例中x的总和,y的值也是围绕“+”运算符的两个网格点实例中y的总和。

第9到12行定义了__str__() method which is called when we try to print the object. That’s also a built in method. But we are going to overload the method so that it prints in our specified format.

第14行和第15行,我们创建了两个网格点对象,即point1和point2。现在,看16号线。使用“+”运算符添加类GridPoint类的两个实例,并将其指定为GridPoint的另一个实例。Python操作符重载有助于实现这一点。所以,当第17行显示的输出如下图所示时,不要感到惊讶。

数学运算符列表

下面是一个操作符列表,可以用类似的方式重载并与python操作符重载一起使用。

操作员说明方法
+添加__添加(自己,其他)
–个;减法__sub UUUU(自己,其他)
*乘法__穆尔(自我,他人)
/真除法__truediv_uu(自我,其他)
//楼层划分__地板(自己,其他)
%余数__mod UUUUU(自己,其他)
**权力__权力(自我,他人)
&安培;按位与__和(自我,他人)
|按位或__或(自我、他人)
^按位异或__异或(自我,其他)

在Python中重载关系运算符

在python中,关系运算符的重载方式非常类似。但不同的是,这些运算符通常返回true/false,而不是返回对象的另一个实例。让我们来举个例子。

        
class GridPoint:  
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  
  
    def __gt__(self, other):  # Overloading the greater than operator
        return self.x > other.x  
# Returns true if value of x in the left operand is greater than that in the right one. Returns false otherwise
  
    def __str__(self):  
        string = str(self.x)  
        string = string + ", " + str(self.y)  
        return string  
  
point1 = GridPoint(3, 5)  
point2 = GridPoint(-1, 4)  
if point1 > point2:  # Compares with the overloaded __gt__() method
    print("point1 is greater than point2")  
else:  
    print("point1 is not greater than point2")  

请看第6行,其中加载了“大于”运算符。如果传统的“>;”运算符左侧的操作数大于右侧的操作数,则返回true。我们将使用这个属性来比较类GridPoint的两个实例。

然后在第17行中,我们将比较GridPoint类的对象,以获得一个布尔类型值,该值将确定第一个对象是否具有更大的值“x”。在本例中,关系运算符返回true,因为3大于-1。因此,程序将打印“point1大于point2”。

python中更多的关系运算符

下面是一个可以以相同方式重载的关系运算符的列表。

操作员说明方法
>;大于__gt(自己,其他)
>=大于或等于__葛优(自己,其他)
<;少于__他(自我,他人)
<=小于或等于__乐悻(自我,他人)
==等于__情商(自我,他人)
!=不等于__不(自我,其他)

这就是今天关于python中操作符重载的全部内容。希望很快能和你一起学习更多的教程。编码快乐!

参考文献:Python.org网站文件