python中重载运算符_Python中的运算符重载

python中重载运算符

Operators are used in Python to perform specific operations on the given operands. The operation that any particular operator will perform on any predefined data type is already defined in Python.

在Python中使用运算符对给定的操作数执行特定的操作。 Python中已经定义了任何特定运算符将对任何预定义数据类型执行的操作。

Each operator can be used in a different way for different types of operands. For example, + operator is used for adding two integers to give an integer as a result but when we use it with float operands, then the result is a float value and when + is used with string operands then it concatenates the two operands provided.

每个运算符可以以不同的方式用于不同类型的操作数。 例如, +运算符用于将两个整数相加以得到一个整数结果,但是当我们将其与float操作数一起使用时,则结果为浮点值,而当+字符串操作数一起使用时,它将连接所提供的两个操作数。

This different behaviour of a single operator for different types of operands is called Operator Overloading. The use of + operator with different types of operands is shown below:

单个运算符针对不同类型的操作数的这种不同行为称为运算符重载 。 下面显示了+运算符与不同类型的操作数的使用:

>>> x=10
>>> y=20
>>> x+y
30

>>> z=10.4
>>> x+z
20.4

>>> s1 = 'hello '
>>> s2 = 'world'
>>> s1+s2
'hello world'

+运算符可以添加任何内容吗? (Can + Operator Add anything?)

The answer is No, it cannot. Can you use the + operator to add two objects of a class. The + operator can add two integer values, two float values or can be used to concatenate two strings only because these behaviours have been defined in python.

答案是否定的。 您可以使用+运算符添加一个类的两个对象吗? +运算符可以添加两个整数值,两个浮点值或仅可用于连接两个字符串,因为这些行为已在python中定义。

So if you want to use the same operator to add two objects of some user defined class then you will have to defined that behaviour yourself and inform python about that.

因此,如果要使用相同的运算符添加某个用户定义类的两个对象,则必须自己定义该行为并通知python。

If you are still not clear, let's create a class and try to use the + operator to add two objects of that class,

如果仍然不清楚,让我们创建一个类,然后尝试使用+运算符添加该类的两个对象,

class Complex:
    def __init__(self, r, i):
        self.real = r
        self.img = i

c1 = Complex(5,3)
c2 = Complex(2,4)
print("sum = ", c1+c2)

Traceback (most recent call last): File "/tmp/sessions/1dfbe78bb701d99d/main.py", line 7, in print("sum = ", c1+c2) TypeError: unsupported operand type(s) for +: 'Complex' and 'Complex'

追溯(最近一次通话最近):文件“ /tmp/sessions/1dfbe78bb701d99d/main.py”,第7行 print(“ sum =”,c1 + c2)TypeError:+不支持的操作数类型:'Complex'和'Complex'

So we can see that the + operator is not supported in a user-defined class. But we can do the same by overloading the + operator for our class Complex. But how can we do that?

因此,我们可以看到用户定义的类中不支持+运算符。 但是我们可以通过为类Complex重载+运算符来做到这一点。 但是,我们该怎么做呢?

Python中的特殊功能 (Special Functions in Python)

Special functions in python are the functions which are used to perform special tasks. These special functions have __ as prefix and suffix to their name as we see in __init__() method which is also a special function. Some special functions used for overloading the operators are shown below:

python中的特殊功能是用于执行特殊任务的功能。 正如我们在__init__()方法中看到的那样,这些特殊功能以__作为前缀和名称的后缀,这也是一个特殊功能。 下面显示了一些用于使运算符超载的特殊功能:

数学运算符 (Mathematical Operator)

Below we have the names of the special functions to overload the mathematical operators in python.

在下面,我们有一些特殊函数的名称,它们可以重载python中的数学运算符。

NameSymbolSpecial Function
Addition+ __add__(self, other)
Subtraction- __sub__(self, other)
Division/ __truediv__(self, other)
Floor Division// __floordiv__(self, other)
Modulus(or Remainder)% __mod__(self, other)
Power** __pow__(self, other)
名称 符号 特殊功能
加成 + __add__(self, other)
减法 - __sub__(self, other)
/ __truediv__(self, other)
楼层部 // __floordiv__(self, other)
模量(或余数) % __mod__(self, other)
功率 ** __pow__(self, other)

赋值运算符 (Assignment Operator)

Below we have the names of the special functions to overload the assignment operators in python.

下面我们有一些特殊函数的名称,它们可以重载python中的赋值运算符。

NameSymbolSpecial Function
Increment+= __iadd__(self, other)
Decrement-= __isub__(self, other)
Product*= __imul__(self, other)
Division/= __idiv__(self, other)
Modulus%=__imod__(self, other)
Power**= __ipow__(self, other)
名称 符号 特殊功能
增量 += __iadd__(self, other)
减量 -= __isub__(self, other)
产品 *= __imul__(self, other)
/= __idiv__(self, other)
模量 %= __imod__(self, other)
功率 **= __ipow__(self, other)

关系运算符 (Relational Operator)

Below we have the names of the special functions to overload the relational operators in python.

下面我们有特殊功能的名称来重载python中的关系运算符。

NameSymbolSpecial Function
Less than< __lt__(self, other)
Greater than> __gt__(self, other)
Equal to==__eq__(self, other)
Not equal != __ne__(self, other)
Less than or equal to<=__le__(self, other)
Greater than or equal to> =__gt__(self, other)
名称 符号 特殊功能
少于 < __lt__(self, other)
比...更棒 > __gt__(self, other)
等于 == __eq__(self, other)
不相等 != __ne__(self, other)
小于或等于 <= __le__(self, other)
大于或等于 > = __gt__(self, other)

It's time to see a few code examples where we actually use the above specified special functions and overload some operators.

现在该来看一些代码示例,在这些示例中,我们实际上使用了上面指定的特殊功能并重载了一些运算符。

重载+运算符 (Overloading + operator)

In the below code example we will overload the + operator for our class Complex,

在下面的代码示例中,我们将为类Complex重载+运算符,

class Complex:
    # defining init method for class
    def __init__(self, r, i):
        self.real = r
        self.img = i

    # overloading the add operator using special function
    def __add__(self, sec):
        r = self.real + sec.real
        i = self.img + sec.img
        return complx(r,i)

    # string function to print object of Complex class
    def __str__(self):
        return str(self.real)+' + '+str(self.img)+'i'

c1 = Complex(5,3)
c2 = Complex(2,4)
print("sum = ",c1+c2)

sum = 7 + 7i

总和= 7 + 7i

In the program above, __add__() is used to overload the + operator i.e. when + operator is used with two Complex class objects then the function __add__() is called.

在上面的程序中, __add__()用于重载+运算符,即,当+运算符与两个Complex类对象一起使用时,将调用__add__()函数。

__str__() is another special function which is used to provide a format of the object that is suitable for printing.

__str__()是另一个特殊功能,用于提供适合打印的对象格式。

重载<运算符 (Overloading < operator)

Now let's overload the less than operator so that we can easily compare two Complex class object's values by using the less than operaton <.

现在,让我们重载低于运营商,使我们可以很容易地比较两个Complex用比operaton少类对象的值<

As we know now, for doing so, we have to define the __lt__ special function in our class.

众所周知,为此,我们必须在类中定义__lt__特殊功能。

演示地址

Based on your requirement of comparing the class object, you can define the logic for the special functions for overriding an operator. In the code above, we have given precedence to the real part of the complex number, if that is less then the whole complex number is less, if that is equal then we check for the imaginary part.

根据比较类对象的要求,可以定义特殊功能的逻辑以覆盖运算符。 在上面的代码中,我们给复数的实部赋予了优先级,如果该乘积小于实数,则整个复数较小,如果相等,则检查虚部。

结论 (Conclusion)

Overloading operators is easy in python using the special functions and is less confusion too.

使用特殊功能在python中重载运算符很容易,并且也减少了混乱。

翻译自: https://www.studytonight.com/python/python-operator-overloading

python中重载运算符

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值