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)`
这些是您可以用来重载运算符的方法。
推荐阅读
- html - 带有嵌套 ul 标签的多级菜单
- python - 如何使用python映射熊猫数据框中的值
- amazon-web-services - 匿名用户可以将文件上传到 aws s3 吗?
- arrays - 在spring mongo模板中按数组大小检索所有数据
- kubernetes - 使用 Kubernetes 入口设置“Cache-Control”标头
- javascript - 带有 \\n 的 Javascript JSON.stringify 文本不显示带有换行符的 Javascript 字符串
- ggplot2 - 从 ggplot2 地图中删除国家的政治边界
- linux - rsync only 文件夹,里面没有文件,也没有扫描文件
- character-encoding - 缩短 GUID
- unix - 通过 awk / xargs 替换定义字符串中的变量值