0

I have a class that contains a list of instances of another class. How do I delete the content of the parts attribute so I can create a new instance of the outer class that has an empty parts attribute? And what am I not understanding that is causing this behaviour?

class MyOuterClass():

    parts = []

    def add_part(self, name):

        new_part = self.SubClass()
        new_part.name = name
        self.parts.append(new_part)

        return new_part

    class SubClass():

        name = ""

for n in range(1,4):

    c = MyOuterClass()
    c.add_part(str(n))

    print(c.parts)

    c.parts = []

    del c

    try:
        print(c)
    except Exception as e:
        print(e)

running this code shows it remembering previous list of parts, even though I have deleted the outer class::

[<__main__.MyOuterClass.SubClass object at 0x101949c10>]
name 'c' is not defined
[<__main__.MyOuterClass.SubClass object at 0x101949c10>, <__main__.MyOuterClass.SubClass object at 0x101949a10>]
name 'c' is not defined
[<__main__.MyOuterClass.SubClass object at 0x101949c10>, <__main__.MyOuterClass.SubClass object at 0x101949a10>, <__main__.MyOuterClass.SubClass object at 0x101949dd0>]
name 'c' is not defined
PhoebeB
  • 8,069
  • 8
  • 55
  • 74

0 Answers0