[Python] Python destructing two objects when (I think) I only destructed one [closed]

Discussão em 'Python' iniciado por Stack, Dezembro 9, 2024.

  1. Stack

    Stack Membro Participativo

    I am learning Python and decided to create a simple class to help me understand. The class is for Tennis Balls. I have a class attribute of num_balls, and instance attributes of serial_number and age.

    I create two instances of the TennisBall class and name them 'a' and 'b'. When I call the destructor for 'a', instance 'b' also gets destructed.

    class TennisBall:
    ball_count = 0

    def __init__(self, serial_number, age):
    self.serial_number = serial_number
    self.age = age
    print("New Tennis Ball created {}!".format(self.serial_number))
    TennisBall.ball_count +=1

    def __del__(self):
    print("Tennis ball {} has been deleted :(".format(self.serial_number))
    TennisBall.ball_count -= 1




    a = TennisBall(1234, 0)
    print("Num balls: {} ".format(TennisBall.ball_count))

    b = TennisBall(2345, 0)
    print("Num balls: {} ".format(TennisBall.ball_count))

    del a
    print("Num balls after del ball a: {} ".format(TennisBall.ball_count))


    I destructed instance 'a' and it was deleted as expected. However, instance 'b' was also destructed, even though I did not call that.

    I tried destructing 'b' instead and again both 'a' and 'b' were destructed.

    Continue reading...

Compartilhe esta Página