Class variable inheritance

Lie Ryan lie.1296 at gmail.com
Fri Sep 11 17:00:37 EDT 2009


HPJ wrote:
> And by the way, the reason I've come across this problem at all is
> because I have something like this:
> 
> class A:
>   class X:
>     n = 'a'
>   x = X()
> 
> class B(A):
>   class X(A.X):
>     n = 'b'
> # x = X()
> 
> The line commented out was originally not there, but I found out I had
> to add it if I wanted B().x.n to be 'b' instead of 'a'.
> 
> I might be wrong, but aren't there some (non-obscure) OOP language in
> which the equivalent code (without the out-commented line) would have
> made B().x an object of type B.X instead of A.X?

Perhaps in a language where classes attribute are declarative. Not in 
python where class attributes are executable statements.

Note that when the python interpreter meets this statement:

class B(P):
     def foo(self):
         print('ab')
     X = 'f'

the compiler sees a class statement -> create a new blank class
                                     -> assign P as the new class' parent
                                     -> *execute* the class' body

# new context
the compiler sees a def statement -> *compile* the def's body
                                   -> assign the compiled body to B.foo
the compiler sees X = 'f' statement -> assign 'f' to B.X
# exit the new context

                                     -> assign the new class to B

Your problem is related to how the interpreter *execute* a class 
definition rather than the name resolution.




More information about the Python-list mailing list