[General lang] how to call a parent
Jeff Epler
jepler at unpythonic.net
Sun Jun 15 12:53:12 EDT 2003
What is the "parent" of an object? For instance given
class Z: pass
a = Z()
b = Z()
c = Z()
a.kids = [c]
b.kids = [c]
it's clear that c is-a kid of a, and c is-a kid of b, so what is c's
parent? Python can have any sort of directed graph for objects, not just a
tree, so the language doesn't define the parent of an object.
However, if you work only with objects of your own devising, you can keep
track of the parent/child relationship:
class FamilyTree:
def __init__(self, name, parent=None):
self.name = name
self.kids = []
self.parent = None
if parent is not None: parent.add(self)
def add(self, kid):
if kid.parent:
kid.parent.kids.remove(kid)
kid.parent = self
self.kids.append(kid)
def newkid(self, name):
return FamilyTree(name, self)
def __repr__(self):
return ("<%s with %d kids>"
% (self.name, len(self.kids)))
>>> from ft import FamilyTree
>>> a = FamilyTree("a")
>>> b = FamilyTree("b", a) # or b = a.newkid("b")
>>> c = FamilyTree("c", b)
>>> print b, b.parent # B has a kid, and the right parent
<b with 1 kids> <a with 1 kids>
>>> print c, c.parent # C has no kids and the right parent
<c with 0 kids> <b with 1 kids>
>>> a.add(c) # A adopts C (B was bad parent?)
>>> print b, b.parent # B now has 1 kid, A now has 2
<b with 0 kids> <a with 2 kids>
>>> print c.parent # sure enough, C's parent is A
<a with 2 kids>
a = FamilyTree("a")
b = FamilyTree("b", a)
c = FamilyTree("c", b)
Jeff
More information about the Python-list
mailing list