I'm having trouble understanding scope of a variable in a subclass

Amaury Forgeot d'Arc afaNOSPAM at neuf.fr
Thu Dec 28 03:09:07 EST 2006


Hello,

Pyenos a écrit :
> Thanks for clarifying the definitions of nested class and
> subclass. However, it did not solve my original problem, and I have
> redefined my question:
> 
> class Class1:
>     class Class2:
>         class Class3:
>             def __init__(self):
>                 self.var="var"
>             class Class4:
>                 print Class1.Class2.Class3.var
> 
> This code gives me the error:
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in Class1
>   File "<stdin>", line 3, in Class2
>   File "<stdin>", line 6, in Class3
>   File "<stdin>", line 7, in Class4
> NameError: name 'Class1' is not defined
> 
> I have tried:
> 
> class Class1:
>         class Class2:
>                 def __init__(self):
>                         var="var"
> print Class1.Class2().var #this works
> 
> And, this worked. It is very strange that nested loop somehow fails to
> work when the innermost class has indentation level greater than two.

This has nothing to do with the indentation level.
But please try to copy exactly the code that you actually executed.

- Your first example fails, but with a different error message
(hint: the "print" statement is not inside a function, so it is executed 
as soon as the interpreter sees it - before it defines the classes.)
And it differs with your second example because the parentheses are 
missing after the name "Class3".

- Your second example does not work as you say. 'var' is a local 
variable and cannot be accessed from the outside. I suppose you actually 
entered something like:
                       self.var="var"
which works indeed.

Again, it is difficult to guess what you are trying to do.

-- 
Amaury



More information about the Python-list mailing list