A brief discussion on keyword del and instance method __del__(self)

巴扎黑
Release: 2016-11-26 10:53:47
Original
1476 people have browsed it

There are many special methods in Python similar to __del__(self). Some of them, such as __gt__(), __le__(), etc., can guess their approximate functions from their names, but some cannot be guessed at will (of course Maybe it’s just me), for example, the __del__() and del that are about to appear here. I used to think that when del an object, __del__() will be called, but after failing the written test again and again , I just started to review these more subtle points ^_^!
Enough chatter and get to the point!
We know that del deletes an object. In fact, to be precise, it should decrease the reference count of the object by one. But note that __del__() will not be called every time it is called, because __del__() will be called when the reference count of the object drops to 0, as evidenced by the example:

>>> class C:
        def __del__(self):
        print("I'm vanishing...")
>>> c = C()
>>> b = c            # 注意,此时对C()的引用计数为2
>>> del b
>>>                  # 瞧,什么输出都没有,说明__del__()并没调用
>>> del c
I'm vanishing...     # 引用计数降为0后才被调用
>>>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!