geekdoc-python-zh/docs/pythonguru/020.md

5.0 KiB
Raw Permalink Blame History

Python 运算符重载

原文: https://thepythonguru.com/python-operator-overloading/


于 2020 年 1 月 7 日更新


您已经看到可以使用+运算符添加数字,并同时连接字符串。 这是可能的,因为int类和str类都重载了+运算符。 运算符实际上是在各个类中定义的方法。 运算符的定义方法称为运算符重载。 例如:要对自定义对象使用+运算符,您需要定义一个名为__add__的方法。

让我们举个例子来更好地理解

import math

class Circle:

    def __init__(self, radius):
        self.__radius = radius

    def setRadius(self, radius):
        self.__radius = radius

    def getRadius(self):
        return self.__radius

    def area(self):
        return math.pi * self.__radius ** 2

    def __add__(self, another_circle):
        return Circle( self.__radius + another_circle.__radius )

c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a    method named __add__
print(c3.getRadius())

预期输出

4
5
9

import math

class Circle:

    def __init__(self, radius):
        self.__radius = radius

    def setRadius(self, radius):
        self.__radius = radius

    def getRadius(self):
        return self.__radius

    def area(self):
        return math.pi * self.__radius ** 2

    def __add__(self, another_circle):
        return Circle( self.__radius + another_circle.__radius )

c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a    method named __add__
print(c3.getRadius()) 

在上面的示例中,我们添加了__add__()方法,该方法允许使用+运算符添加两个圆形对象。 在__add__()方法内部,我们正在创建一个新对象并将其返回给调用者。

Python 还有许多其他特殊方法,例如__add__(),请参见下面的列表。

运算符 函数 方法说明
+ __add__(self, other) 加法
* __mul__(self, other) 乘法
- __sub__(self, other) 减法
% __mod__(self, other) 余数
/ __truediv__(self, other) 除法
< __lt__(self, other) 小于
<= __le__(self, other) 小于或等于
== __eq__(self, other) 等于
!= __ne__(self, other) 不等于
> __gt__(self, other) 大于

>=__ge__(self, other),大于或等于[index]__getitem__(self, index),索引运算符in__contains__(self, value),检查成员资格len__len__(self),元素数str__str__(self)的字符串表示形式

下面的程序使用上面提到的一些函数来重载运算符。

import math

class Circle:

    def __init__(self, radius):
        self.__radius = radius

    def setRadius(self, radius):
        self.__radius = radius

    def getRadius(self):
        return self.__radius

    def area(self):
        return math.pi * self.__radius ** 2

    def __add__(self, another_circle):
        return Circle( self.__radius + another_circle.__radius )

    def __gt__(self, another_circle):
        return self.__radius > another_circle.__radius

    def __lt__(self, another_circle):
        return self.__radius < another_circle.__radius

    def __str__(self):
        return "Circle with radius " + str(self.__radius)

c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2
print(c3.getRadius())

print( c3 > c2) # Became possible because we have added __gt__ method

print( c1 < c2) # Became possible because we have added __lt__ method

print(c3) # Became possible because we have added __str__ method

预期输出

4
5
9
True
True
Circle with radius 9

import math

class Circle:

    def __init__(self, radius):
        self.__radius = radius

    def setRadius(self, radius):
        self.__radius = radius

    def getRadius(self):
        return self.__radius

    def area(self):
        return math.pi * self.__radius ** 2

    def __add__(self, another_circle):
        return Circle( self.__radius + another_circle.__radius )

    def __gt__(self, another_circle):
        return self.__radius > another_circle.__radius

    def __lt__(self, another_circle):
        return self.__radius < another_circle.__radius

    def __str__(self):
        return "Circle with radius " + str(self.__radius)

c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2
print(c3.getRadius())

print( c3 > c2) # Became possible because we have added __gt__ method

print( c1 < c2) # Became possible because we have added __lt__ method

print(c3) # Became possible because we have added __str__ method 

下一课是继承和多态