class question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sittner@lkb.ens.fr

    #1

    class question

    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).
    how do i do this?
    thanks,
    t

  • Scott David Daniels

    #2
    Re: class question

    sittner@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.WeakVal ueDictionary()
    if dad is not None:
    dad.add_kid(sel f)
    if mom is not None:
    mom.add_kid(sel f)

    def children(self):
    return self._kids.valu es()

    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@a cm.org

    Comment

    Working...