user3044330
user3044330

Reputation: 63

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.

Upvotes: 6

Views: 821

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43126

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

Upvotes: 3

jai ganesh
jai ganesh

Reputation: 1

class Foo: 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).

Upvotes: 0

Related Questions