I am learning Python from here.
In Section 9.6 (Private Variables and Class-local References), the last paragraph states that:
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.
I do not understand what they mean. Please provide an explanation or give me some examples to demonstrate this concept.
Imagine you have a class with a local reference:
class Foo:
__attr= 5
Inside the class, this attribute can be referenced as __attr
:
class Foo:
__attr= 5
print(__attr) # prints 5
But not outside of the class:
print(Foo.__attr) # raises AttributeError
But it's different if you use eval
, exec
, or execfile
inside the class:
class Foo:
__attr= 5
print(__attr) # prints 5
exec 'print(__attr)' # raises NameError
This is explained by the paragraph you quoted. exec
does not consider Foo
to be the "current class", so the attribute cannot be referenced (unless you reference it as Foo._Foo__attr
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With