On the python destructor
I have never used the python destructor before. Today I played with it after seeing a question on Zhihu.
Note that the first two classes have the same name “test”, while the third one is named “test1”.
Here are two observations:
a
is destructed first. In its destructor, the static class variabletest.tag
is set to ‘0000’.b
is destructed last. Its destructor prints out the the static class variabletest.tag
as ‘0000’.
The reason is:
- When
a
is destructed, the ‘test
’ class ofa
is destructed, before the__del__
function is called, so thetest.tag = ...
in its destructor is actually referring to the ‘test
’ class ofb
(they have the sameid
). That’s why whenb
is destructed, thetest.tag
has a value pf ‘0000’ rather than ‘2222’.
Note that when b
is being destructed, the test.tag
still exists, which
means the class can be destructed later than the object itself.
b
is destructed later than c
, because in the definition of test1
it
refers to test.tag
(which is not a typo). But in general, the order of
calling the destructors does not have a simple pattern.