python - 我如何知道在 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()
解决方案
推荐阅读
- python - Flask - 带有动态标签的切换按钮
- cordova - Ionic 3 和 Firebase 存储
- javascript - Javascript和HTML;从 URL 获取页面
- javascript - 错误的 switch case 语法,但适用于除 Safari 以外的所有浏览器
- c# - 性能计数器良好做法
- c# - 在同一行的自动映射器中初始化 Ilist
- google-apps-script - Google-sheets 脚本查找数据并使用高级 Google 服务显示在弹出消息中
- java - 通过 Java Web Start 9 和 10 的 JApplet 似乎将宽度设置为高度
- asp.net-mvc - 如何在 Visual Studio 2017 中创建 MVC 项目?
- javascript - 发现“不可信”事件的起源