首页 > 解决方案 > 有没有办法改变python解释代码的方式?

问题描述

有没有办法改变 python 解释你输入的内容的方式?例如,交换“==”(布尔值)和“=”(变量赋值)的作用?

标签: python

解决方案


是的,你绝对可以改变python中运算符的含义。它被称为运算符重载。

使用 Python 魔术方法或特殊函数进行运算符重载

`

Binary Operators:  OPERATOR MAGIC METHOD 
+   __add__(self, other)
–   __sub__(self, other)
*   __mul__(self, other)
/   __truediv__(self, other)
//  __floordiv__(self, other)
%   __mod__(self, other)
**  __pow__(self, other)

Comparison Operators :

OPERATOR    MAGIC METHOD
<   __lt__(self, other)
>   __gt__(self, other)
<=  __le__(self, other)
>=  __ge__(self, other)
==  __eq__(self, other)
!=  __ne__(self, other)

Assignment Operators :

OPERATOR    MAGIC METHOD
-=  __isub__(self, other)
+=  __iadd__(self, other)
*=  __imul__(self, other)
/=  __idiv__(self, other)
//= __ifloordiv__(self, other)
%=  __imod__(self, other)
**= __ipow__(self, other)

Unary Operators :

OPERATOR    MAGIC METHOD
–   __neg__(self, other)
+   __pos__(self, other)
~   __invert__(self, other)`

这些是您可以用来重载运算符的方法。


推荐阅读