uwon
uwon

Reputation: 47

Python using a del keyword inside a function

I have a Game class which creates an object of games. I want to create a function that deletes an object when a user inputs a name of a game. I created a function that I thought it will do what I want to do but it doesn't. Please tell me what is wrong.

    class Game:
    def __init__(self, game_title, publisher, num_of_sales):
        self._chart_position = 4
        self._game_title = game_title
        self._publisher = publisher
        self._num_of_sales = num_of_sales

    def set_game_title(self, game_title):
        self._game_title = game_title

    def set_chart_position(self, chart_position):
        self._chart_position = chart_position

    def set_num_of_sales(self, num_of_sales):
        self._num_of_sales = num_of_sales

    def get_game_details(self):
        if self._chart_position <= 5:
            return self._chart_position, self._game_title, self._publisher, self._num_of_sales

def game_del(game):
    del game

cup = Game("cupfight", "A", 13)
game_del(cup)

Upvotes: 1

Views: 177

Answers (1)

Masked Man
Masked Man

Reputation: 2538

Python is a garbage-collected language so you don't need to delete anything (except for the very rare cases); If you have an object in memory, e.g. Game in this case and assigned the reference to it to a variable in this case cup it will reside in memory as long as the cup is in scope (in this example the entire program lifetime). But if you assign something else to the cup variable (anything, e.g. cup = None) there's nothing referencing the Game object so it will be scheduled for garbage collection.

Upvotes: 1

Related Questions