简体   繁体   中英

Deleting Object in Globals using Class Method

I am trying to build a class method where I can delete an instance of a class object from system memory.The combined operator assignment gives me the desired output, however I still cannot delete the instance of the class object bananna from globals() or dir(). What am I doing wrong?

Code:

class Budget:
    def __init__(self,category):
        self.category=category
        self.amount=0
    
    def total():
        pass

    def percentage_breakdown():
        pass

    def category_percentage_breakdown():
        pass

class Food:
    def __init__(self,name, amount):
        self.name=name
        self.amount=amount

    def add_to_budget(self,Budget):
        if Budget.category=='Food':
            Budget.amount+=self.amount
        else:
            print(' I know you want to cheat your budget but thats not going to happen')

    def remove_from_budget(self,Budget):
        if Budget.category=='Food':
            Budget.amount-=self.amount
            for name in dir():
                if name==self:
                    del globals()[self]
        else:
            print('You are not gonna feel any less guilty about starving yourself')


food=Budget('Food')
bananna= Food('bananna',3)
print(bananna)
bananna.add_to_budget(food)
print(food.amount)
bananna.remove_from_budget(food)
print(food.amount)
print(globals())
print(dir()) 

Output:

>>> bananna= Food('bananna',3)
>>> print(bananna)
<__main__.Food object at 0x000001E361E1EEB0>
>>> bananna.add_to_budget(food)
>>> print(food.amount)
3
>>> bananna.remove_from_budget(food)
>>> print(food.amount)
0
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Budget': <class '__main__.Budget'>, 'Food': <class '__main__.Food'>, 'food': <__main__.Budget object at 0x000001E361E1EE80>, 'bananna': <__main__.Food object at 0x000001E361E1EEB0>, 'entertainment': <__main__.Budget object at 0x000001E361E1EDF0>}
>>> print(dir())
['Budget', 'Food', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'bananna', 'entertainment', 'food'] 

The del statement deletes names, not objects. An object may be garbage collected as result of a del command, but only if the variable deleted holds the last reference to the object, or if the object becomes unreachable.

that is why your object not deleting cuz there is still a reference exists and CPython will not delete the object until there are no more references to the object.
the right way to do this is like what Peter said in his comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM