'Clear class of all instances?

I wrote a program where class instances are created automatically out of input data. Each time I run the program however, new instances are created but with the same data.

Is there a way to clear a class after the program has run, in order to prevent double instances?



Solution 1:[1]

You could try creating a list of instances when your class is created.

class Foo:
  instances = []
  
  def __init__(self):
    self.__class__.instances.append(self)

Then when you want to delete all of the objects of class Foo, you can use del to delete them while iterating through the list.

for i,v in enumerate(Foo.instances):
  del v

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1