Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private Variables and Class-local References

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.

like image 601
user3044330 Avatar asked Jul 27 '16 07:07

user3044330


1 Answers

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).

like image 58
Aran-Fey Avatar answered Oct 21 '22 06:10

Aran-Fey