运算符重载python
Welcome to the tutorial on Python Operator Overloading. As we have already learnt about Python Class, we are going to learn another interesting feature of object oriented python today.
欢迎使用Python操作符重载教程。 正如我们已经了解Python Class一样 ,今天我们将学习面向对象python的另一个有趣的功能。
Python Operator overloading enables us to use mathematical, logical and bitwise operators on python objects just like any primitive data type.
Python运算符重载使我们能够像对待任何原始数据类型一样,在python对象上使用数学,逻辑和按位运算符。
For example, you can easily add two numbers 3 and 5 with + operator, i.e 3 + 5. And the result is 8.
例如,您可以使用+运算符轻松地将两个数字3和5相加,即3 +5。结果为8。
But what if you want to add two circles (object of a Circle class) and make a circle having twice the radius? Or what if you want to add two cartesian grid points to yield another point with the same ‘+’ operator? Python operator overloading allows you to perform operations just like those.
但是,如果您想添加两个圆(Circle类的对象)并使半径为两倍的圆呢? 或者,如果您想添加两个笛卡尔网格点以使用相同的“ +”运算符产生另一个点,该怎么办? Python运算符重载使您可以像执行那些操作一样执行操作。
Now, let’s see an example of overloading mathematical operator.
现在,让我们看一个重载数学运算符的例子。
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
Lines 1 to 4 indicates the declaration of the class GridPoint
and definition of constructor method. Let’s have a look at lines 6 and 7.
第1至4行表示GridPoint
类的声明和构造方法的定义。 让我们看一下第6行和第7行。
def __add__(self, other): # Equivalent of + operator
return GridPoint(self.x + other.x, self.y + other.y)
When we use ‘+’ operator as mathematical addition operation, the __add__()
method is implicitly called.
当我们使用'+'运算符作为数学加法运算时, __add__()
方法被隐式调用。
So, if we are to add two objects of the class GridPoint, we must re-define this method. So, here we need to create another instance of GridPoint class whose value of x is the summation of x in the two GridPoint instances around the ‘+’ operator and value of y is also the summation of y in the two GridPoint instances around the ‘+’ operator.
因此,如果要添加GridPoint类的两个对象,则必须重新定义此方法。 因此,在这里我们需要创建另一个GridPoint类的实例,其x的值是在'+'运算符附近的两个GridPoint实例中x的总和,而y的值也是在''周围的两个GridPoint实例中y的总和。 +'运算符。
Lines 9 to 12 defines the __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.
第9至12行定义了__str__()
方法,当我们尝试打印对象时会调用该方法。 这也是一个内置方法。 但是我们将重载该方法,以便它以指定的格式打印。
Lines 14 and 15, we’ve created two objects of GridPoint, namely point1 and point2. Now, watch Line 16. Two instances of the class GridPoint class are added using ‘+’ operator and assigned as another instance of GridPoint. Python operator overloading helps you do this. So, don’t get surprised when the 17th line shows an output like below image.
第14和15行,我们创建了GridPoint的两个对象,即point1和point2。 现在,看第16行。使用'+'运算符添加GridPoint类的两个实例,并将它们分配为GridPoint的另一个实例。 Python运算符重载可以帮助您做到这一点。 因此,当第17行显示如下图所示的输出时,请不要感到惊讶。
Here is a list of operators which can be overloaded and used with python operator overloading in a similar way.
这是可以重载的运算符列表,并且可以类似的方式与python运算符重载一起使用。
Operator | Description | Method |
+ | Addition | __add__(self, other) |
– | Subtraction | __sub__(self, other) |
* | Multiplication | __mul__(self, other) |
/ | True Division | __truediv__(self, other) |
// | Floor Division | __floordiv__(self, other) |
% | Remainder | __mod__(self, other) |
** | Power | __pow__(self, other) |
& | Bitwise AND | __and__(self, other) |
| | Bitwise OR | __or__(self, other) |
^ | Bitwise XOR | __xor__(self, other) |
操作员 | 描述 | 方法 |
+ | 加成 | __add __(自己,其他) |
– | 减法 | __sub __(自己,其他) |
* | 乘法 | __mul __(其他) |
/ | 真师 | __truediv __(自己,其他) |
// | 楼层部 | __floordiv __(自己,其他) |
% | 余 | __mod __(自己,其他) |
** | 功率 | __pow __(自己,其他) |
和 | 按位与 | __和__(自己,其他) |
| | 按位或 | __或__(自己,其他) |
^ | 按位异或 | __xor __(自己,其他) |
Relational operators are overloaded in a very similar way in python. But the difference is, those operators often return true/false instead of another instance of the object. Let’s work with an example.
关系运算符在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')
Look at line 6, where the ‘greater than’ operator has been loaded. The conventional ‘>’ operator returns true if the operand in the left side of it is greater than the right one. We are going to use this property to compare two instances of class GridPoint.
查看第6行,已加载“大于”运算符。 如果左侧的操作数大于右侧的操作数,则常规的'>'运算符将返回true。 我们将使用此属性来比较GridPoint类的两个实例。
Then in line 17, we are comparing the objects of the class GridPoint to obtain a boolean type value which will determine whether the first object has the greater value of ‘x’. In this case, the relational operator returns true as 3 is greater than -1. As a result the program prints ‘point1 is greater than point2’.
然后在第17行中,我们比较GridPoint类的对象以获得布尔类型值,该值将确定第一个对象是否具有较大的'x'值。 在这种情况下,当3大于-1时,关系运算符返回true。 结果是程序打印“ point1大于point2”。
Here is a list of relational operators that can be overloaded in the same way.
这是可以以相同方式重载的关系运算符的列表。
Operator | Description | Method |
> | Greater than | __gt__(self, other) |
>= | Greater than or equal to | __ge__(self, other) |
< | Less than | __lt__(self, other) |
<= | Less than or equal to | __le__(self, other) |
== | Equal to | __eq__(self, other) |
!= | Not equal to | __ne__(self, other) |
操作员 | 描述 | 方法 |
> | 比...更棒 | __gt __(自己,其他) |
> = | 大于或等于 | __ge __(自己,其他) |
< | 少于 | __lt __(自己,其他) |
<= | 小于或等于 | __le __(自己,其他) |
== | 等于 | __eq __(自己,其他) |
!= | 不等于 | __ne __(自己,其他) |
That’s all for today about operator overloading in python. Hope to be with you with more tutorials very soon.
Happy Coding!
今天就有关python中的运算符重载。 希望很快就会有更多教程与您同在。
编码愉快!
Reference: Python.org Docs
参考: Python.org文档
翻译自: https://www.journaldev.com/14637/python-operator-overloading
运算符重载python