Reputation: 23
The problem I'm facing is that I have person_1
Instance
And I create a destroyed
static method that should delete any instance
That passed to it as y parameter but the instance still exists.
I want person_1
to be removed and python should give an error message.
Thanks in advance
class population:
""" This class is used
To adds and delete people """
x = 0
def __init__(self,name):
self.name = name
print(f'Initilaizing {name}\n Total_persons. {population.x}')
population.x += 1
@classmethod
# This class method is used to adds a new instance to the population class.
def constructor(cls, y):
population.x += 1
return cls(y)
@staticmethod
# This static method is used to remove an instance from the population class.
def destroyed(k):
del k
population.x -= 1
print(f'Total_persons after destroyed procedure. {population.x}')
person_1 = population('mohammed')
print(person_1.name)
population.destroyed(person_1)
print(person_1.name)
Upvotes: 1
Views: 723
Reputation: 1840
The problem you're running into is caused by the fact that del k
in your destroyed function is killing off only that instance of the object, not the one outside of the function scope. Python allows you to add functionality to a deleting an object with the __del__
function.
Implementing as such:
def __del__(self):
population.x -= 1
print(f'Total_persons after destroyed procedure. {population.x}')
Will allow you to replace population.destroyed(person_1)
with del person_1
to get the result you're looking for.
Upvotes: 1