A
A
Akmat2017-06-23 09:01:08
Python
Akmat, 2017-06-23 09:01:08

Special method __del_ in Python3, don't understand when it is called?

The question is I have a special __del__ method inside the class.
The book A Byte of Python says, link to book
page 114-115.
__del__ is only fired when the object is no longer used, it is not known in advance when this moment will come.
Let's go back to my code, after creating an instance, __del__ is immediately called,
so
I create

droid1 = Robot('R2-D2')
droid1.sayHi()

After that, __del__ is immediately called.
And if after droid1 we create another droid2 object, then after droid1 __del__ is not immediately called
droid1 = Robot('R2-D2')
droid1.sayHi()

droid2 = Robot('R2-D2')
droid2.sayHi()

and after droid2 __del__ is called.
It is written in the book, the object is explicitly destroyed
del droid1
del droid2

Everything is called for me without destruction using __del__ which is wrong or in order.
I don't understand.
Here's the code.
class Robot:
  population = 0

  def __init__(self,name):
    self.name = name
    print('(Инициализация {0})'.format(self.name))
    Robot.population += 1

  def __del__(self):
    print('{0} Уничтожается!'.format(self.name))
    Robot.population -= 1

    if Robot.population == 0:
      print('{0} Был последним.'.format(self.name))
    else:
      print('Осталось {0:d} работающих роботов'.format(Robot.population))

  def sayHi(self):
    print('Приветствую! Мои хозяева называют меня {0}.'.format(self.name))

  def howMany():
    print('У нас {0:d} роботов.'.format(Robot.population))

  howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')
droid1.sayHi()
droid1.howMany()
print()
droid2 = Robot('cp-120')
droid2.sayHi()
droid2.howMany()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-06-23
@Akmat

Objects are removed if
You have the third option. In the first case, the program ends immediately after the creation of the first droid, memory is cleared, all objects are deleted. In the second case, the same thing happens after the creation of the second droid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question