Inheritance and Inner/Nested Classes

Paul Morrow pm_mon at yahoo.com
Mon Jul 12 09:43:30 EDT 2004


Peter Hansen wrote:
> Paul Morrow wrote:
> 
>> ######################################
>> class Parent(object):
>>     class Foo(object):
>>         baz = 'hello from Parent.Foo'
>>
>> class Child(Parent):
>>     #Foo.baz = 'hello from Child.Foo'
>>     pass
> 
> 
> Here you want "Parent.Foo.bax = ..." instead.
> 
> What are you actually trying to do?  This is unusual code,
> I think...
> 
> -Peter

I'm trying to override the 'baz' class attribute in the Child.Foo 
subclass, so that when I do...

x1 = Parent.Foo()
x2 = Child.Foo()

... x1 and x2 have different internal states (different values for the 
baz attribute).  Without nested classes, the following code...

#####################################
class Parent(object):
     baz = 'hello from Parent'

class Child(Parent):
     baz = 'hello from Child'

print Parent.baz
print Child.baz
#####################################

...produces what I would expect...

hello from Parent
hello from Child

...but apparently my thinking is wrong on nested class definitions.  It 
seems odd that, according to dir(Child), Foo is inherited by Child, but 
  I can't refer to Foo in Child's class definition.  And even if I 
could, it wouldn't be a *copy* of the Parent's Foo that Child has, but 
rather Parent's Foo itself --- changing Foo.baz in Child changes Foo.baz 
in Parent, which is not what I want.

Thx.




More information about the Python-list mailing list