gpt4 book ai didi

python - python函数/方法调用有什么静态的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:24 25 4
gpt4 key购买 nike

asking a question about reflection我问:

Nice answer. But there is a difference between saying myobject.foo() and x = getattr(myobject, "foo"); x();. Even if it is only cosmetic. In the first the foo() is compiled in statically. In the second, the string could be produced any number of ways. – Joe 1 hour ago

哪个得到了答案:

Eh, potato / solanum tuberosum... in python, niether is statically compiled, so they are more or less equivalent. – SWeko 1 hour ago

我知道 Python 对象的成员存储在字典中并且一切都是动态的,但我假设给出以下代码:

class Thing():
def m(self):
pass

t = Thing()

生成 .pyc 时,以下代码将以某种方式进行静态编译:

t.m()

即编译器知道 m() 的地址,所以在运行时没有点绑定(bind)。那个或运行时将缓存后续查找。

而这总是涉及查字典:

meth = getattr(t, "m")
meth()

是否所有调用都被视为字典中的字符串查找?或者这两个示例实际上是相同的?

最佳答案

它们并不完全相同,但它们都是字典查找,如反汇编程序所示 dis.dis .

请特别注意 LOAD_ATTR 指令,它按名称动态查找属性。根据文档,它“将 TOS [堆栈顶部] 替换为 getattr(TOS, co_names[namei])”。

>>> from dis import dis
>>> dis(lambda: t.m())
1 0 LOAD_GLOBAL 0 (t)
3 LOAD_ATTR 1 (m)
6 CALL_FUNCTION 0
9 RETURN_VALUE
>>> dis(lambda: getattr(t, 'm')())
1 0 LOAD_GLOBAL 0 (getattr)
3 LOAD_GLOBAL 1 (t)
6 LOAD_CONST 0 ('m')
9 CALL_FUNCTION 2
12 CALL_FUNCTION 0
15 RETURN_VALUE

关于python - python函数/方法调用有什么静态的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com