Reputation: 5
Hey guys I have a problem with deleting class instances. I have a class which whenever an instance is created, it starts a while loop. But when I try to delete that instance the loop still runs no matter what. How can I delete it properly so no sign of that instance left? could you help me please?
I have already tried to make an instace, then append ist to a list, then delete it from that list but it didn't work.
class Foo:
delf __init__(self):
self.x = 0
while True:
self.x += 1
def die(self):
instances.remove(self)
instances = []
foo = Foo()
instances.append(foo)
foo.die()
Upvotes: 0
Views: 123
Reputation: 20500
Not sure why you have a while True
loop in the constructor, the constructor will never exit and instances.append(foo)
will be unreachable. Assuming you put while True
by mistake, you can use del https://docs.python.org/3/tutorial/datastructures.html#the-del-statement
class Foo:
def __init__(self):
self.x = 0
foo = Foo()
print(foo.x)
#0
del foo #this deletes the object
print(foo)
#NameError: name 'foo' is not defined
Upvotes: 1