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

var*_*ble 5 python python-3.x

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

请有人举个例子来帮助我理解下面的引文:

请注意,传递给 exec() 或 eval() 的代码不会将调用类的类名视为当前类;这类似于全局语句的效果,其效果同样仅限于字节编译在一起的代码。同样的限制适用于 getattr()、setattr() 和 delattr(),以及直接引用dict时。

jua*_*aga 5

它基本上告诉您双下划线的“魔力”不适用于execor eval,因此请考虑以下示例:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

同样,对于getattr等:

>>> getattr(f, '__bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
Run Code Online (Sandbox Code Playgroud)