1

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)
sophros
  • 14,672
  • 11
  • 46
  • 75
MartinEG
  • 47
  • 3
  • 2
    What are you trying to achieve? in `game_del` function the game is a local passed by value copy of cup and you are deleting that local copy not where it is pointing to! and as python is a garbage-collected language you don't need to be worried about deleting your variables. – Masked Man Dec 02 '19 at 16:11
  • Thank you for your reply. I understand but then when does the reference count for cup becomes 0 without deleting it? – MartinEG Dec 02 '19 at 16:38
  • When there's no reference to it in the current scope either directly or indirectly and as you defined the `cup` in the *module* scope and the module in this case is the **main program** its reference count would be 0 after the program finishes. – Masked Man Dec 02 '19 at 19:32
  • What I want to do is when the user enters the game name which exists, I want to delete that specific game(object). To do that is not the best way to use del? If not, how do I make the ref count 0 so that it can be garbage collected? I understand the concept of garbage collection but I have no idea how to make the ref count 0. – MartinEG Dec 02 '19 at 20:03

1 Answers1

1

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.

Masked Man
  • 2,176
  • 2
  • 22
  • 41