2

Let's say I have the following classes

class Daddy:
    children=[]

    def addChild(self,aChild):
        self.children.append(aChild)

class Child:
    name = ''
    def __init__(self, aName):
        self.name = aName

aChild = Child('Peter')
aDaddy = Daddy()
aDaddy.addChild(aChild)
print aDaddy.children[0].name
del(aDaddy)
anotherDaddy = Daddy()
print anotherDaddy.children[0].name

Daddy() keeps a reference to the object aDaddy, and I get the following output:

Peter
Peter
ilciavo
  • 3,069
  • 7
  • 26
  • 40

1 Answers1

5

children is a class variable (similar to static variables in other languages), so it's shared across all instances of Daddy (same with the name variable in Child).

Initialize it in __init__ instead:

class Daddy:
    def __init__(self):
        self.children = []

    def addChild(self,aChild):
        self.children.append(aChild)
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85