Class variable inheritance
pavlovevidence at gmail.com
Wed Sep 9 09:16:49 CEST 2009
On Sep 8, 11:05 pm, HPJ <henrypija... at gmail.com> 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()
You've nested classes here, that's a whole new layer of complexity.
I would strongly recommend against nesting classes in Python, unless
the inner class is a smallish class (such as a custom exception type)
that doesn't interact with the outer class. It's just that nested
classes don't ever seem to behave like anyone expects them to. Also
you can't take advantage of Python's lexical scoping with nested
classes (unlike, for instance, Java) so there really isn't much
benefit to nesting them.
> 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'.
Hm, even if class B did get copies of class A's attributes, B().x.n
would still return 'a'. It seems as if you expect class B to re-
execute A's statements in B's context, or something. That's not how
it works at all.
(Now if you define self.x=X() inside of __init__, that's a different
> 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?
Maybe. For some languages this might be an obvious behavior, but
Python would have different circumstances so it isn't so obvious (or
More information about the Python-list