class question

Scott David Daniels scott.daniels at
Sat Mar 17 23:43:53 CET 2007

sittner at wrote:
> Hello there,
> i am pretty new to object-oriented programming and i have a question:
> let's say i have a simple class such as:
> class father:
>      age=...
>      name=....
>      def abcd.....
>      class son(father):
>             age=....
>             name=....
>             def efgh:
> or any other heirarchic structure of class and subclasses.
> i would like to list or print the data content of a given instance of the
> subclass, all the way up (e.g. if sam is jack's son, so i would like to
> get their names and ages and use the class as a data structure for that
> matter).

You misunderstand Python's classes.  There is little, if any advantage
to defining a class inside another class.

How about:
     import weakref  # to keep everyone from being immortal.

     class Person(object):
         def __init__(self, age, name, dad=None, mom=None):
    = name
             self.age = age
    = dad
    = mom
             self._kids = weakref.WeakValueDictionary()
             if dad is not None:
             if mom is not None:

         def children(self):
             return self._kids.values()

         def add_kid(self, child):
             assert self.age > child.age
             self._kids[id(child)] = child

         def __repr__(self):
	    return '%s(%s)' % (, self.age)

     guy = Person(age=28, name='George')
     gal = Person(age=31, name='Martha')
     kid = Person(age=1, name='Ellen', dad=guy, mom=gal)
     print '%s of %s and %s.' % (kid,,
     print "%s's kids: %s." % (guy, guy.children())
     print "%s's kids: %s." % (gal, gal.children())

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list