Inheritance and Inner/Nested Classes

Andrew Bennetts andrew-pythonlist at puzzling.org
Mon Jul 12 16:58:15 CEST 2004


On Mon, Jul 12, 2004 at 10:28:08AM -0400, Paul Morrow wrote:
[...]
> 
> ...would work, but I was hoping to avoid having to create the 
> constructor methods as well as (re)declare the inner class in the 
> descendent/child classes.  It looks like class attributes take care of 
> the former...
> 
> #####################################
> class Parent(object):
>     class Foo(object):
>         baz = 'hello from Parent.Foo'
> 
> class Child(Parent):
>     class Foo(Parent.Foo):
>         baz = 'hello from Child.Foo'
> 
> x1 = Parent.Foo()
> x2 = Child.Foo()
> print x1.baz
> print x2.baz
> #####################################
> 
> ... but I don't see any way to avoid the later.
> 
> I know that this is still a contrived example, but just imagine that the 
>  Foo inner class represents some customization category, and baz is a 
> customization variable in that category.

Well, the problem is that the way you say you want spell it is mutating a
shared object:

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

If you want 'Foo' in Child to be a different object to the Foo in Parent,
then you need to somehow make it be a different object, which means
assigning to 'Foo' in Child's namespace.  The simplest and clearest way to
do that is to explicitly subclass with "class Foo(Parent.Foo): ...".

-Andrew.




More information about the Python-list mailing list