0

So I am following a tutorial and have the following code:

import random

class Coin:
    def __init__(self, rare = False, clean = True, heads = True, **kwargs):

        for key, value in kwargs.items():
            setattr(self,key,value)

        self.heads = heads
        self.is_rare = rare
        self.is_clean = clean

        if self.is_rare:
            self.value = self.original_value * 1.25
        else:
            self.value = self.original_value

        if self.is_clean:
            self.colour = self.clean_colour
        else:
            self.colour = self = self.rusty_colour

    def rust(self):
        self.colour = self.rusty_colour

    def clean(self):
        self.colour = "self.clean_colour"

    def __del__(self):
        print("Coin Spent!")

    def flip(self):
        heads_options = [True, False]
        choice = random.choice(heads_options)
        self.heads = choice

class Pound(Coin):
    def __init__(self):
        data = {
            "original_value": 1.00,
            "clean_colour": "gold",
            "rusty_colour":"greenish",
            "num_edges": 1,
            "diameter": 22.5,
            "thickness": 3.15,
            "mass": 9.5
        }
        super().__init__(**data)

one_pound_coin = Pound()
print(one_pound_coin.colour)
one_pound_coin.rust()
print(one_pound_coin.colour)

Upon running that code in PyCharm, it shows the following output:

gold
greenish
Coin Spent!

The 'gold' and 'greenish' are direct results of the last 4 lines of code, that's all as intended. I am puzzled as to why it states 'Coin Spent!' however, as I am not using the 'del' method (I believe) it should only print('Coin Spent!) when I am using del one_pound_coin for example. Now even if all I use for a driver code is simply 'one_pound_coin = Pound()' it prints 'Coin Spent!'.

Getting started with Python and coding in general. Thanks for the help in advance! I am specifically interested in understanding why the code is running the way it is.

  • 3
    In Python, the `__del__()` method is referred to as a destructor method. It is called after an object's garbage collection occurs, which happens after all references to the item have been destroyed. – Cow Jan 05 '23 at 07:13
  • 2
    Python cleans up objects when the script ends by calling their `__del__` method, if any, even though it is not guaranteed that the method would always be called, per the documentation. – blhsing Jan 05 '23 at 07:15
  • 2
    The `__del__` method is not where you should put important business logic like coins having been spent. – deceze Jan 05 '23 at 07:17
  • 1
    Does this answer your question? [What is the \_\_del\_\_ method and how do I call it?](https://stackoverflow.com/questions/1481488/what-is-the-del-method-and-how-do-i-call-it) This is a good answer to what it is and how it's used. – Cow Jan 05 '23 at 07:21

0 Answers0