Search code examples
pythonobjectdel

How to delete old references in Python?


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

Solution

  • 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)