Python 教程之运算符(6)—— 运算符重载

820 阅读4分钟

我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第13篇文章,点击查看活动详情

运算符重载意味着赋予超出其预定义的操作含义的扩展含义。例如运算符 + 用于添加两个整数以及连接两个字符串和合并两个列表。这是可以实现的,因为 '+' 运算符被 int 类和 str 类重载。您可能已经注意到,相同的内置运算符或函数对不同类的对象显示不同的行为,这称为运算符重载

# Python 程序显示 + 运算符用于不同目的。

print(1 + 2)

# 连接两个字符串
print("Geeks"+"For")

# Product two numbers
print(3 * 4)

# 重复字符串
print("Geeks"*4)

输出

3
GeeksFor
12
GeeksGeeksGeeksGeeks

输出  

3
GeeksFor
12
GeeksGeeksGeeksGeeks

如何重载Python中的运算符?  
考虑到我们有两个对象,它们是一个类的物理表示(用户定义的数据类型),我们必须使用二进制“+”运算符添加两个对象,它会引发错误,因为编译器不知道如何添加两个对象. 因此,我们为运算符定义了一个方法,该过程称为运算符重载。我们可以重载所有现有的运算符,但不能创建新的运算符。为了执行运算符重载,Python 提供了一些特殊函数或魔术函数,当它与特定运算符关联时会自动调用这些函数。例如,当我们使用 + 运算符时,会自动调用魔术方法 add,其中定义了 + 运算符的操作。
在 Python 中重载二进制 + 运算符:  
当我们在用户定义的数据类型上使用运算符时,会自动调用与该运算符关联的特殊函数或魔术函数。改变运算符的行为就像改变方法或函数的行为一样简单。您在类中定义方法,运算符根据方法中定义的行为工作。当我们使用 + 运算符时,会自动调用魔术方法 add ,其中定义了 + 运算符的操作。通过改变这个魔法方法的代码,我们可以给 + 运算符赋予额外的意义。 
代码 1:

# Python 程序说明如何重载二元 + 运算符

class A:
	def __init__(self, a):
		self.a = a

	# adding two objects
	def __add__(self, o):
		return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")

print(ob1 + ob2)
print(ob3 + ob4)

输出

3
GeeksFor

输出 : 

3
GeeksFor

代码 2:

# 使用二元 + 运算符重载执行两个复数相加的 Python 程序。

class complex:
	def __init__(self, a, b):
		self.a = a
		self.b = b

	# 添加两个对象
	def __add__(self, other):
		return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)

输出

(3, 5)

输出 : 

(3, 5)

在 Python 中重载比较运算符:

# Python程序重载比较运算符

class A:
	def __init__(self, a):
		self.a = a
	def __gt__(self, other):
		if(self.a>other.a):
			return True
		else:
			return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
	print("ob1 is greater than ob2")
else:
	print("ob2 is greater than ob1")

输出 : 

ob2 is greater than ob1

重载相等和小于运算符:

# Python程序重载相等和小于运算符

class A:
	def __init__(self, a):
		self.a = a
	def __lt__(self, other):
		if(self.a<other.a):
			return "ob1 is lessthan ob2"
		else:
			return "ob2 is less than ob1"
	def __eq__(self, other):
		if(self.a == other.a):
			return "Both are equal"
		else:
			return "Not equal"
				
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)

ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)

输出 : 

ob1 is lessthan ob2
Not equal

用于运算符重载的 Python 魔术方法或特殊函数

二元运算符:

运算符Magic Method
+add(自己,其他)
sub(自己,其他)
*****mul(自己,其他)
/truediv(自我,其他)
//floordiv(自我,其他)
%mod(自我,其他)
******pow(自己,其他)
>>rshift(自我,其他)
<<lshift(自我,其他)
&(自己,其他)
(自己,其他)
xor(自我,其他)

比较运算符:

运算符Magic Method
<lt(自己,其他)
>gt(自己,其他)
<=le(自己,其他)
>=ge(自己,其他)
==eq(自我,其他)
!=ne(自己,其他)

赋值运算符:

运算符Magic Method
-=isub(自我,其他)
+=iadd(自己,其他)
*=imul(自我,其他)
/=idiv(自我,其他)
//=ifloordiv(自我,其他)
%=imod(自己,其他)
**=ipow(自我,其他)
>>=irshift(自我,其他)
<<=ilshift(自己,其他)
&=iand(自己,其他)
**=**ior(自己,其他)
^=ixor(自我,其他)

一元运算符:

运算符Magic Method
neg(自我)
+pos(自我)
~反转(自我)

注意: 不能更改运算符的运算符数量。例如。您不能将一元运算符重载为二元运算符。以下代码将引发语法错误。

# 尝试将 ~ 运算符重载为二元运算符的 Python 程序

class A:
	def __init__(self, a):
		self.a = a

	# Overloading ~ operator, but with two operands
	def __invert__(self, other):
		return "This is the ~ operator, overloaded as binary operator."


ob1 = A(2)
ob2 = A(3)

print(ob1~ob2)