Inheritance and Inner/Nested Classes

Peter Hansen peter at engcorp.com
Mon Jul 12 15:50:14 CEST 2004


Paul Morrow wrote:

> Peter Hansen wrote:
>> What are you actually trying to do?  This is unusual code,
>> I think...
> 
> 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).  

Sorry, let me try the question in a different way.  What end
goal, without reference to *how* you think you want to achieve it,
are you trying to achieve?  You've posted what are obviously
contrived examples.  I can't see the purpose here... other
than "different internal states", but if that's all it is
you don't need to have an inner class to do it (as you show
you know by the following:)

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.

Exactly... so what *do* you want?

By the way, have you considered just using *instances* instead
of mucking directly in the classes themselves?  That's the usual
way to go about object-oriented programming (and probably why it's
not called "class-oriented programming" :-).  If you did that, you
would use the initializer __init__() to set up the different state
by creating an instance of the Foo class inside the Parent's
initializer, then making the appropriate changes inside the
Child's initializer after calling the Parent's...

Another question is why bother with the nested class?  Why
not just stick Foo outside both classes?  (Doing this would
first require doing what I suggested in the previous paragraph,
however...but it might show you why what you are doing now
is sort of weird and maybe pointless.)

-Peter



More information about the Python-list mailing list