Issue
I want to know how you can delete a instance within the class. I am trying del self
, but it doesn't seem to work. Here's my code:
class Thing:
def __init__(self):
self.alive = True
self.age = 0
def update(self):
self.age += 1
def kill(self):
if self.age >= 10:
del self
def all(self):
self.update()
self.kill()
things = []
for i in range(0, 10):
thing.append(Thing())
while True:
for thing in things:
thing.all()
I specifically want to delete the instance inside the class. I have also replaced del self
with self = None
, but this statement doesn't seem to have any effect. How can I do this?
Solution
You can't do quite what you're asking for. Python's del
statement doesn't work like that. What you can do however, is mark your instance as dead (you already have an attribute for this!), and then later, filter the list of objects to drop the dead ones:
class Thing:
def __init__(self):
self.alive = True # use this attribute!
self.age = 0
def update(self):
self.age += 1
def kill(self):
if self.age >= 10:
self.alive = False # change it's value here rather than messing around with del
def all(self):
self.update()
self.kill()
things = []
for i in range(0, 10):
things.append(Thing())
while True:
for thing in things:
thing.all()
things = [thing for thing in things if thing.alive] # filter the list
Note that the loops at the end of this code run forever with no output, even after all the Thing
instances are dead. You might want to modify that so you can tell what's going on, or even change the while
loop to check if there's are any objects left in things
. Using while things
instead of while True
might be a reasonable approach!
Answered By - Blckknght
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.