京公网安备 11010802034615号
经营许可证编号:京B2-20210330
原题 | Unravelling binary arithmetic operations in Python
作者 | Brett Cannon
译者 | 豌豆花下猫
来源 | Python猫
声明 | 本翻译是出于交流学习的目的,基于 CC BY-NC-SA 4.0 授权协议。为便于阅读,内容略有改动。
大家对我解读属性访问的博客文章反应热烈,这启发了我再写一篇关于 python 有多少语法实际上只是语法糖的文章。在本文中,我想谈谈二元算术运算。
具体来说,我想解读减法的工作原理:a - b。我故意选择了减法,因为它是不可交换的。这可以强调出操作顺序的重要性,与加法操作相比,你可能会在实现时误将 a 和 b 翻转,但还是得到相同的结果。
查看 C 代码
按照惯例,我们从查看 CPython 解释器编译的字节码开始。
>>> def sub(): a - b ... >>> import dis >>> dis.dis(sub) 1 0 LOAD_GLOBAL 0 (a) 2 LOAD_GLOBAL 1 (b) 4 BINARY_SUBTRACT 6 POP_TOP 8 LOAD_CONST 0 (None) 10 RETURN_VALUE
看起来我们需要深入研究 BINARY_SUBTRACT 操作码。翻查 Python/ceval.c 文件,可以看到实现该操作码的 C 代码如下:
case TARGET(BINARY_SUBTRACT): {
PyObject *right = POP();
PyObject *left = TOP();
PyObject *diff = PyNumber_Subtract(left, right);
Py_DECREF(right);
Py_DECREF(left);
SET_TOP(diff);
if (diff == NULL)
goto error;
DISPATCH();
}
来源:https://github.com/python/cpython/blob/6f8c8320e9eac9bc7a7f653b43506e75916ce8e8/Python/ceval.c#L1569-L1579
这里的关键代码是PyNumber_Subtract(),实现了减法的实际语义。继续查看该函数的一些宏,可以找到binary_op1() 函数。它提供了一种管理二元操作的通用方法。
不过,我们不把它作为实现的参考,而是要用Python的数据模型,官方文档很好,清楚介绍了减法所使用的语义。
从数据模型中学习
通读数据模型的文档,你会发现在实现减法时,有两个方法起到了关键作用:__sub__ 和 __rsub__。
1、__sub__()方法
当执行a - b 时,会在 a 的类型中查找__sub__(),然后把 b 作为它的参数。这很像我写属性访问的文章 里的__getattribute__(),特殊/魔术方法是根据对象的类型来解析的,并不是出于性能目的而解析对象本身;在下面的示例代码中,我使用_mro_getattr() 表示此过程。
因此,如果已定义 __sub__(),则 type(a).__sub__(a,b) 会被用来作减法操作。(译注:魔术方法属于对象的类型,不属于对象)
这意味着在本质上,减法只是一个方法调用!你也可以将它理解成标准库中的 operator.sub() 函数。
我们将仿造该函数实现自己的模型,用 lhs 和 rhs 两个名称,分别表示 a-b 的左侧和右侧,以使示例代码更易于理解。
# 通过调用__sub__()实现减法
def sub(lhs: Any, rhs: Any, /) -> Any:
"""Implement the binary operation `a - b`."""
lhs_type = type(lhs)
try:
subtract = _mro_getattr(lhs_type, "__sub__")
except AttributeError:
msg = f"unsupported operand type(s) for -: {lhs_type!r} and {type(rhs)!r}"
raise TypeError(msg)
else:
return subtract(lhs, rhs)
2、让右侧使用__rsub__()
但是,如果 a 没有实现__sub__() 怎么办?如果 a 和 b 是不同的类型,那么我们会尝试调用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右侧)。
当操作的双方是不同类型时,这样可以确保它们都有机会尝试使表达式生效。当它们相同时,我们假设__sub__() 就能够处理好。但是,即使两边的实现相同,你仍然要调用__rsub__(),以防其中一个对象是其它的(子)类。
3、不关心类型
现在,表达式双方都可以参与运算!但是,如果由于某种原因,某个对象的类型不支持减法怎么办(例如不支持 4 - “stuff”)?在这种情况下,__sub__ 或__rsub__ 能做的就是返回 NotImplemented。
这是给 Python 返回的信号,它应该继续执行下一个操作,尝试使代码正常运行。对于我们的代码,这意味着需要先检查方法的返回值,然后才能假定它起作用。
# 减法的实现,其中表达式的左侧和右侧均可参与运算
_MISSING = object()
def sub(lhs: Any, rhs: Any, /) -> Any:
# lhs.__sub__
lhs_type = type(lhs)
try:
lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")
except AttributeError:
lhs_method = _MISSING
# lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
try:
lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")
except AttributeError:
lhs_rmethod = _MISSING
# rhs.__rsub__
rhs_type = type(rhs)
try:
rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")
except AttributeError:
rhs_method = _MISSING
call_lhs = lhs, lhs_method, rhs
call_rhs = rhs, rhs_method, lhs
if lhs_type is not rhs_type:
calls = call_lhs, call_rhs
else:
calls = (call_lhs,)
for first_obj, meth, second_obj in calls:
if meth is _MISSING:
continue
value = meth(first_obj, second_obj)
if value is not NotImplemented:
return value
else:
raise TypeError(
f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
)
4、子类优先于父类
如果你看一下__rsub__() 的文档,就会注意到一条注释。它说如果一个减法表达式的右侧是左侧的子类(真正的子类,同一类的不算),并且两个对象的__rsub__() 方法不同,则在调用__sub__() 之前会先调用__rsub__()。换句话说,如果 b 是 a 的子类,调用的顺序就会被颠倒。
这似乎是一个很奇怪的特例,但它背后是有原因的。当你创建一个子类时,这意味着你要在父类提供的操作上注入新的逻辑。这种逻辑不一定要加给父类,否则父类在对子类操作时,就很容易覆盖子类想要实现的操作。
具体来说,假设有一个名为 Spam 的类,当你执行 Spam() - Spam() 时,得到一个 LessSpam 的实例。接着你又创建了一个 Spam 的子类名为 Bacon,这样,当你用 Spam 去减 Bacon 时,你得到的是 VeggieSpam。
如果没有上述规则,Spam() - Bacon() 将得到 LessSpam,因为 Spam 不知道减掉 Bacon 应该得出 VeggieSpam。
但是,有了上述规则,就会得到预期的结果 VeggieSpam,因为 Bacon.__rsub__() 首先会在表达式中被调用(如果计算的是 Bacon() - Spam(),那么也会得到正确的结果,因为首先会调用 Bacon.__sub__(),因此,规则里才会说两个类的不同的方法需有区别,而不仅仅是一个由 issubclass() 判断出的子类。)
# Python中减法的完整实现
_MISSING = object()
def sub(lhs: Any, rhs: Any, /) -> Any:
# lhs.__sub__
lhs_type = type(lhs)
try:
lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")
except AttributeError:
lhs_method = _MISSING
# lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
try:
lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")
except AttributeError:
lhs_rmethod = _MISSING
# rhs.__rsub__
rhs_type = type(rhs)
try:
rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")
except AttributeError:
rhs_method = _MISSING
call_lhs = lhs, lhs_method, rhs
call_rhs = rhs, rhs_method, lhs
if (
rhs_type is not _MISSING # Do we care?
and rhs_type is not lhs_type # Could RHS be a subclass?
and issubclass(rhs_type, lhs_type) # RHS is a subclass!
and lhs_rmethod is not rhs_method # Is __r*__ actually different?
):
calls = call_rhs, call_lhs
elif lhs_type is not rhs_type:
calls = call_lhs, call_rhs
else:
calls = (call_lhs,)
for first_obj, meth, second_obj in calls:
if meth is _MISSING:
continue
value = meth(first_obj, second_obj)
if value is not NotImplemented:
return value
else:
raise TypeError(
f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
)
推广到其它二元运算
解决掉了减法运算,那么其它二元运算又如何呢?好吧,事实证明它们的操作相同,只是碰巧使用了不同的特殊/魔术方法名称。
所以,如果我们可以推广这种方法,那么我们就可以实现 13 种操作的语义:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。
由于闭包和 Python 在对象自省上的灵活性,我们可以提炼出 operator 函数的创建。
# 一个创建闭包的函数,实现了二元运算的逻辑
_MISSING = object()
def _create_binary_op(name: str, operator: str) -> Any:
"""Create a binary operation function.
The `name` parameter specifies the name of the special method used for the
binary operation (e.g. `sub` for `__sub__`). The `operator` name is the
token representing the binary operation (e.g. `-` for subtraction).
"""
lhs_method_name = f"__{name}__"
def binary_op(lhs: Any, rhs: Any, /) -> Any:
"""A closure implementing a binary operation in Python."""
rhs_method_name = f"__r{name}__"
# lhs.__*__
lhs_type = type(lhs)
try:
lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name)
except AttributeError:
lhs_method = _MISSING
# lhs.__r*__ (for knowing if rhs.__r*__ should be called first)
try:
lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name)
except AttributeError:
lhs_rmethod = _MISSING
# rhs.__r*__
rhs_type = type(rhs)
try:
rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name)
except AttributeError:
rhs_method = _MISSING
call_lhs = lhs, lhs_method, rhs
call_rhs = rhs, rhs_method, lhs
if (
rhs_type is not _MISSING # Do we care?
and rhs_type is not lhs_type # Could RHS be a subclass?
and issubclass(rhs_type, lhs_type) # RHS is a subclass!
and lhs_rmethod is not rhs_method # Is __r*__ actually different?
):
calls = call_rhs, call_lhs
elif lhs_type is not rhs_type:
calls = call_lhs, call_rhs
else:
calls = (call_lhs,)
for first_obj, meth, second_obj in calls:
if meth is _MISSING:
continue
value = meth(first_obj, second_obj)
if value is not NotImplemented:
return value
else:
exc = TypeError(
f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}"
)
exc._binary_op = operator
raise exc
有了这段代码,你可以将减法运算定义为 _create_binary_op(“sub”, “-”),然后根据需要重复定义出其它运算。
更多信息
通过本博客的“语法糖”标签,你可以找到更多详解 Python 语法的文章。
更正
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在回归分析的结果解读中,R方(决定系数)是衡量模型拟合效果的核心指标——它代表因变量的变异中能被自变量解释的比例,取值通 ...
2025-12-04在城市规划、物流配送、文旅分析等场景中,经纬度热力图是解读空间数据的核心工具——它能将零散的GPS坐标(如外卖订单地址、景 ...
2025-12-04在CDA(Certified Data Analyst)数据分析师的指标体系中,“通用指标”与“场景指标”并非相互割裂的两个部分,而是支撑业务分 ...
2025-12-04每到“双十一”,电商平台的销售额会迎来爆发式增长;每逢冬季,北方的天然气消耗量会显著上升;每月的10号左右,工资发放会带动 ...
2025-12-03随着数字化转型的深入,企业面临的数据量呈指数级增长——电商的用户行为日志、物联网的传感器数据、社交平台的图文视频等,这些 ...
2025-12-03在CDA(Certified Data Analyst)数据分析师的工作体系中,“指标”是贯穿始终的核心载体——从“销售额环比增长15%”的业务结论 ...
2025-12-03在神经网络训练中,损失函数的数值变化常被视为模型训练效果的“核心仪表盘”——初学者盯着屏幕上不断下降的损失值满心欢喜,却 ...
2025-12-02在CDA(Certified Data Analyst)数据分析师的日常工作中,“用部分数据推断整体情况”是高频需求——从10万条订单样本中判断全 ...
2025-12-02在数据预处理的纲量统一环节,标准化是消除量纲影响的核心手段——它将不同量级的特征(如“用户年龄”“消费金额”)转化为同一 ...
2025-12-02在数据驱动决策成为企业核心竞争力的今天,A/B测试已从“可选优化工具”升级为“必选验证体系”。它通过控制变量法构建“平行实 ...
2025-12-01在时间序列预测任务中,LSTM(长短期记忆网络)凭借对时序依赖关系的捕捉能力成为主流模型。但很多开发者在实操中会遇到困惑:用 ...
2025-12-01引言:数据时代的“透视镜”与“掘金者” 在数字经济浪潮下,数据已成为企业决策的核心资产,而CDA数据分析师正是挖掘数据价值的 ...
2025-12-01数据分析师的日常,常始于一堆“毫无章法”的数据点:电商后台导出的零散订单记录、APP埋点收集的无序用户行为日志、传感器实时 ...
2025-11-28在MySQL数据库运维中,“query end”是查询执行生命周期的收尾阶段,理论上耗时极短——主要完成结果集封装、资源释放、事务状态 ...
2025-11-28在CDA(Certified Data Analyst)数据分析师的工具包中,透视分析方法是处理表结构数据的“瑞士军刀”——无需复杂代码,仅通过 ...
2025-11-28在统计分析中,数据的分布形态是决定“用什么方法分析、信什么结果”的底层逻辑——它如同数据的“性格”,直接影响着描述统计的 ...
2025-11-27在电商订单查询、用户信息导出等业务场景中,技术人员常面临一个选择:是一次性查询500条数据,还是分5次每次查询100条?这个问 ...
2025-11-27对数据分析从业者和学生而言,表结构数据是最基础也最核心的分析载体——CRM系统的用户表、门店的销售明细表、仓库的库存表,都 ...
2025-11-27在业务数据可视化中,热力图(Heat Map)是传递“数据密度与分布特征”的核心工具——它通过颜色深浅直观呈现数据值的高低,让“ ...
2025-11-26在企业数字化转型中,业务数据分析师是连接数据与决策的核心纽带。但“数据分析师”并非单一角色,从初级到高级,其职责边界、能 ...
2025-11-26