[Tutor] Class attributes & append method

Zak Arntson zak@harlekin-maus.com
Fri Jun 13 17:41:02 2003


I've created a class, PyFictObject, which has two attributes: parent and
children. The objects are arranged in a tree with one parent and many
children. So a room (like the cellar) is a parent to a bunch of children
(pipe, box, ground). I got some helper methods to work, but weird stuff
happened. Here's the working code:

###
class PyFictObject:
    parent = None
    children = []

    def __init__(self, name):
        self.name = name

    def setParent(self, newParent):
        if self.parent != newParent and \
                (self.__class__ == PyFictObject or \
                 PyFictObject in self.parent.__class__.__bases__):
            if (self.parent):
                self.parent.children.remove(self)
            self.parent = newParent
            newParent.addChild(self)

    def addChild(self, newChild):
        if newChild not in self.children:
            self.children = self.children + [newChild]

pipe = PyFictObject('pipe')
cellar = PyFictObject('cellar')

pipe.setParent(cellar)

###

This code works great. But if I use the following (and my first two tries):

###
    def addChild(self, newChild):
        if newChild not in self.children:
            self.children += [newChild]
###

###
    def addChild(self, newChild):
        if newChild not in self.children:
            self.children.append(newChild)
###

Both cellar AND pipe have children = [pipe]!! Why is this? I'm guessing
some sort of "self" confusion?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em