私有变量和 Class-local 引用
Private Variables and Class-local References
我正在向 here 学习 Python。
在第 9.6 节(私有变量和 Class-局部引用)中,最后一段指出:
Notice that code passed to exec, eval() or execfile() 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.
我不明白他们的意思。请提供解释或给我一些例子来证明这个概念。
假设您有一个带有本地引用的 class:
class Foo:
__attr= 5
在 class 中,此属性可以引用为 __attr
:
class Foo:
__attr= 5
print(__attr) # prints 5
但不在class之外:
print(Foo.__attr) # raises AttributeError
但如果在class:
中使用eval
、exec
或execfile
就不一样了
class Foo:
__attr= 5
print(__attr) # prints 5
exec 'print(__attr)' # raises NameError
您引用的段落对此进行了解释。 exec
不认为 Foo
是“当前 class”,因此无法引用该属性(除非您将其引用为 Foo._Foo__attr
)。
class 富:
Foo._Foo__attr= 5
print(Foo._Foo__attr) # prints 5
exec 'print(Foo._Foo__attr)' # CORRECTED REFERENCE, PRINTS OUTPUT 5
# exec does not consider Foo to be
#the "current class",
# so the private attribute cannot be referenced
#(unless you reference it as Foo._Foo__attr).
我正在向 here 学习 Python。
在第 9.6 节(私有变量和 Class-局部引用)中,最后一段指出:
Notice that code passed to exec, eval() or execfile() 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.
我不明白他们的意思。请提供解释或给我一些例子来证明这个概念。
假设您有一个带有本地引用的 class:
class Foo:
__attr= 5
在 class 中,此属性可以引用为 __attr
:
class Foo:
__attr= 5
print(__attr) # prints 5
但不在class之外:
print(Foo.__attr) # raises AttributeError
但如果在class:
中使用eval
、exec
或execfile
就不一样了
class Foo:
__attr= 5
print(__attr) # prints 5
exec 'print(__attr)' # raises NameError
您引用的段落对此进行了解释。 exec
不认为 Foo
是“当前 class”,因此无法引用该属性(除非您将其引用为 Foo._Foo__attr
)。
class 富: Foo._Foo__attr= 5
print(Foo._Foo__attr) # prints 5
exec 'print(Foo._Foo__attr)' # CORRECTED REFERENCE, PRINTS OUTPUT 5
# exec does not consider Foo to be
#the "current class",
# so the private attribute cannot be referenced
#(unless you reference it as Foo._Foo__attr).