Inheritance and Inner/Nested Classes

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


On Mon, Jul 12, 2004 at 09:43:30AM -0400, Paul Morrow wrote:
> 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...

I'm understanding what you want to do correctly, I guess you could do:

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

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

i.e. Parent.Foo is a class that just happens to be stored in as an attribute
of Parent, and so if you want to override it, you have to do so directly.
The fact that you're thinking of them as "nested" doesn't come into it,
except for referencing it.

-Andrew.




More information about the Python-list mailing list