Answer the question
In order to leave comments, you need to log in
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()
droid1 = Robot('R2-D2')
droid1.sayHi()
droid2 = Robot('R2-D2')
droid2.sayHi()
del droid1
del droid2
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
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 questionAsk a Question
731 491 924 answers to any question