在第9.6节私人变量和类别 – 地方参考文献中,最后一段指出:
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 Foo:
__attr= 5
在类中,此属性可以作为__attr引用:
class Foo:
__attr= 5
print(__attr) # prints 5
但不是课外:
print(Foo.__attr) # raises AttributeError
但是如果在类中使用eval,exec或execfile则会有所不同:
class Foo:
__attr= 5
print(__attr) # prints 5
exec 'print(__attr)' # raises NameError
您引用的段落对此进行了解释. exec不认为Foo是“当前类”,因此不能引用private属性(除非您将其引用为Foo._Foo__attr).
标签:python,reference,private,local,class
来源: https://codeday.me/bug/20190628/1310571.html