You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何__truediv__未被触发?Python Emulate类魔术方法异常

问题原因与解决方案

核心原因

Python处理运算符对应的魔术方法时,只会在类的层级查找,不会去实例的属性中搜索。

你当前的代码是把原对象(比如整数1)的所有属性(包括__truediv__这类魔术方法)绑定到了Emulate的实例上,这些属于实例属性。当执行one / 2时,Python会直接去Emulate类的__dict__里找__truediv__方法,找不到就抛出类型错误;但显式调用one.__truediv__(2)是直接访问实例上的属性,所以能正常执行。

解决方案

有两种常见的修复方式,根据你的使用场景选择:

方案1:动态给类添加魔术方法(适合单类型模拟)

如果只需要模拟某一种类型的对象,可以在类初始化时把原对象的魔术方法添加到Emulate类中:

class Emulate:
    def __init__(self, obj):
        # 遍历原对象的属性,把魔术方法添加到类层级
        for attr in dir(obj):
            if attr.startswith('__') and attr.endswith('__') and attr != '__class__':
                if not hasattr(Emulate, attr):
                    setattr(Emulate, attr, getattr(obj, attr))
        # 绑定非魔术属性到实例
        for attr in dir(obj):
            if not (attr.startswith('__') and attr.endswith('__')) and attr != '__class__':
                setattr(self, attr, getattr(obj, attr))

方案2:重写__getattr__(通用灵活方案)

通过__getattr__拦截属性访问,当Python在类和实例中找不到目标属性时,自动去原对象中获取:

class Emulate:
    def __init__(self, obj):
        self._obj = obj
    
    def __getattr__(self, attr):
        # 当访问的属性不存在时,从原对象中获取
        return getattr(self._obj, attr)

这个方案更灵活,支持模拟任意类型的对象,而且不会污染类的属性空间。测试一下:

one = Emulate(1)
print(one / 2)  # 输出 0.5
print(one + 3)  # 输出 4

内容的提问来源于stack exchange,提问作者The Thonnu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:09:21