0

What is wrong with my code!

Hello, can you help me in this OOP code! class Array: def __init__(self, List): self.List = list(List) print(“You created a List.”) def __del__(self): print(“you deleted a list.”) array = Array([3,4]) output: You created a List. You deleted a list. I never use the del keyword so how is the __del__ dunder executed?

4th Oct 2020, 4:01 PM
Shreyaansh
Shreyaansh - avatar
8 ответов
+ 5
__del__is called whenever the object instance is no longer needed (i.e. in garbage collection).
4th Oct 2020, 4:07 PM
Russ
Russ - avatar
+ 3
Whenever it is no longer going to be used. It won't run until you have finished using it.
5th Oct 2020, 4:05 AM
Russ
Russ - avatar
+ 3
Shreyaansh Expanding on what Russ is saying, the object is "no longer needed" when there are no longer any references to that object. This might occur when object references are limited to a call stack and execution context of that call stack has completed or... as in your case, when the program terminates. The garbage collector will essentially call the object destructor prior to clearing it from memory.
5th Oct 2020, 4:41 AM
David Carroll
David Carroll - avatar
+ 1
Like, if we do a = Array([1,2]) while True: a = Array([1]) you would pretty quickly have a billion arrays and your PC would crash because you run out of memory. But you can only ever use the one array that `a` is pointing to and all the others are unusable. Every so often the garbage collector comes and picks up the garbage, which is when __del__ is called.
5th Oct 2020, 6:20 AM
Schindlabua
Schindlabua - avatar
0
oh so you mean whenever we are not changing or using it?
4th Oct 2020, 9:32 PM
Shreyaansh
Shreyaansh - avatar
0
the __del__ will run?
4th Oct 2020, 9:33 PM
Shreyaansh
Shreyaansh - avatar
0
ok
5th Oct 2020, 9:21 PM
Shreyaansh
Shreyaansh - avatar
0
thank you Russ
5th Oct 2020, 9:22 PM
Shreyaansh
Shreyaansh - avatar