首页 > 解决方案 > 我如何知道在 python 语句中调用了哪些魔术方法?

问题描述

文档列出了许多魔术方法。但我认为这还不够。当我这样做时,它没有告诉我调用了哪些方法for x in c

为此,我尝试了一个简单的代码片段来打印每个属性引用:

class Print(object):
    def __getattribute__(self, item):
        print(item)
        return super().__getattribute__(item)

a = Print()

有时它有效:

import pickle
pickle.dumps(a)
# print the following and then raise an error
__reduce_ex__
__reduce__
__getstate__
__class__

然后我知道pickle.dump调用这些魔术方法。

但有时它不起作用:

for x in a:
    continue
# direct error, no print

有什么方法可以告诉在 python 语句中调用了哪些魔法方法?

更新:

似乎 Cpython 绕过getattribute了一些特殊的加速方法的调用。查看special-method-lookup部分了解详细信息。

因此,答案似乎是否定的。我们无法捕获每个属性引用。

举个例子:

class C:
    pass

c = C()
c.__len__ = lambda: 5
len(c)
# TypeError: object of type 'C' has no len()

标签: pythonpython-3.x

解决方案


推荐阅读