class question
Scott David Daniels
scott.daniels at acm.org
Sat Mar 17 18:43:53 EDT 2007
sittner at lkb.ens.fr 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):
self.name = name
self.age = age
self.dad = dad
self.mom = mom
self._kids = weakref.WeakValueDictionary()
if dad is not None:
dad.add_kid(self)
if mom is not None:
mom.add_kid(self)
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.name, 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, kid.dad, kid.mom)
print "%s's kids: %s." % (guy, guy.children())
print "%s's kids: %s." % (gal, gal.children())
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list