gpt4 book ai didi

python - 传递给 exec() 或 eval() 的代码不会将调用类的类名视为当前类

转载 作者:行者123 更新时间:2023-12-01 13:11:48 24 4
gpt4 key购买 nike

我在看这篇文章:https://docs.python.org/3/tutorial/classes.html#private-variables

请有人举一个例子来帮助我理解以下引用:

Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing dict directly.

最佳答案

它基本上是在告诉你双下划线的“魔法”不适用于 execeval ,因此请考虑以下示例:

>>> class Foo:
... def __init__(self):
... self.__bar = 42
... def method0(self):
... return self.__bar * 2
... def method1(self):
... return eval('self.__bar * 2')
...
>>> f = Foo()
>>> f.method0()
84
>>> f.method1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in method1
File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'

同样,对于 getattr等等:
>>> getattr(f, '__bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'

关于python - 传递给 exec() 或 eval() 的代码不会将调用类的类名视为当前类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59495943/

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