Table of Contents
1. Class constructors and destructors
2. Code demonstration
1. Reference changes
2. Class objects only inside the function
3. The class object returned inside the function
1. Use global variables to reference class objects inside functions
Home Backend Development Python Tutorial Detailed example of destruction and release of python class objects

Detailed example of destruction and release of python class objects

Sep 08, 2022 pm 05:37 PM
python

[Related recommendations: Python3 video tutorial ]

1. Class constructors and destructors

  • _init__ The function is the constructor of the Python class. When creating a class object, this function will be automatically called; it can be used to set some initialization information of the object when creating the object. and settings.
  • __del__ The function is the destructor of the Python class. When the life cycle of a class object ends and is destroyed, this function will be automatically called; it is mainly used to release some of the space occupied by the object. resources etc.

2. Code demonstration

1. Reference changes

are as follows, and the implementation code of a demo class is written.

>>> class demo():
...     def __init__(self):
...             print("init class")
...             print(self)
...     def __del__(self):
...             print("del class")
...             print(self)
... 
>>>
Copy after login

When an object of this type is created, it will call the __init__ function and print out "init class";
When an object of this type is destroyed, it will call __del__ Function, print out "del class".

>>> a1 = demo()
init class
<__main__.demo instance at 0x7f328f7c6cb0>
>>> 
>>> a2 = demo()  
init class
<__main__.demo instance at 0x7f328f7c6d40>
>>> 
>>> 
>>> 
>>> a1 = demo()
init class
<__main__.demo instance at 0x7f328f7c6d88>
del class
<__main__.demo instance at 0x7f328f7c6cb0>
>>>
Copy after login

First use the variable a1 to refer to a demo class object. At this time, print out "init class" and the object address referenced by the a1 variable 0x7f328f7c6cb0;

Use variables a2 refers to another demo class object. At this time, "init class" is printed out, as well as the object address referenced by the a2 variable 0x7f328f7c6d40;

The class objects referenced by the a1 and a2 variables are Two different objects 0x7f328f7c6cb0 and 0x7f328f7c6d40.

Finally create a demo class object and use the a1 variable to point to it again. At this time, a1 refers to the new class object, and the reference address is 0x7f328f7c6d88; at the same time, due to the object referenced by a1 before0x7f328f7c6cb0 No one refers to it anymore, so the space of the old demo class object is released, and "del class 0x7f328f7c6cb0" is printed.

2. Class objects only inside the function

>>> def create_demo():
...     inst = demo()
... 
>>> create_demo()
init class
<__main__.demo instance at 0x7f328f7c6cb0>
del class
<__main__.demo instance at 0x7f328f7c6cb0>
>>> 
>>> 
>>> 
>>> create_demo()
init class
<__main__.demo instance at 0x7f328f7c6cb0>
del class
<__main__.demo instance at 0x7f328f7c6cb0>
>>> 
>>> 
>>> 
>>> create_demo()
init class
<__main__.demo instance at 0x7f328f7c6cb0>
del class
<__main__.demo instance at 0x7f328f7c6cb0>
>>>
Copy after login

Define a function create_demo. The function of this function is to create a demo class object and use the inst variable to reference the created class object.

Call the create_demo() function once, you can see that the demo object is created with the address 0x7f328f7c6cb0; then the demo object is released immediately; because the object is only valid within the scope of the create_demo function , the function ends, and the demo object is recycled and released.

Call the create_demo() function again, the phenomenon is the same: the demo object is created with the address 0x7f328f7c6cb0; then the demo object is released immediately.

3. The class object returned inside the function

>>> def return_demo():
...     return demo()
...
Copy after login

Define the function return_demo, which creates a class object internally and returns the created class object.

>>> True
True
>>> return_demo()
init class
<__main__.demo instance at 0x7fc511eb8cb0>
<__main__.demo instance at 0x7fc511eb8cb0>
>>> 
>>> True
del class
<__main__.demo instance at 0x7fc511eb8cb0>
True
>>> 
>>> return_demo()
init class
<__main__.demo instance at 0x7fc511eb8cb0>
<__main__.demo instance at 0x7fc511eb8cb0>
>>> 
>>> 
>>> 
>>> True
del class
<__main__.demo instance at 0x7fc511eb8cb0>
True
>>> 
>>>
Copy after login

You can see that when the function return_demo() is called for the first time, the printed content shows that an object is created at this time, and the object address is 0x7fc511eb8cb0; the function return_demo is used internally The return statement returns the created class object, so when the function returns, the object 0x7fc511eb8cb0 will not be released.

Next, execute a Python statement: True, and see that the object 0x7fc511eb8cb0 is released. Because after the program executes the return_demo() function, it is found that the subsequent program does not reference the object returned by return_demo(), so Python will release the object space 0x7fc511eb8cb0.

The second time you perform the same operation, you can see the same phenomenon.

>>> v1_demo = None
>>> v2_demo = None 
>>> print(v1_demo)
None
>>> print(v2_demo)
None
>>> True
True
>>> 
>>> v1_demo = return_demo() 
init class
<__main__.demo instance at 0x7fc511eb8d88>
>>> 
>>> print(v1_demo)
<__main__.demo instance at 0x7fc511eb8d88>
>>> 
>>> True
True
>>> 
>>> 
>>> v2_demo = return_demo()  
init class
<__main__.demo instance at 0x7fc511eb8dd0>
>>> 
>>> print(v2_demo)
<__main__.demo instance at 0x7fc511eb8dd0>
>>> True
True
>>> 
>>> 
>>> 
>>> 
>>> v1_demo = None
del class
<__main__.demo instance at 0x7fc511eb8d88>
>>> 
>>> print(v1_demo)
None
>>>
Copy after login

The phenomenon of this code segment is basically the same as that of the previous code segment.

As you can see, v1_demo and v2_demo refer to class objects, so the values ​​of v1_demo and v2_demo are no longer None.

Finally, we reset v1_demo to None. At this time, the object 0x7fc511eb8d88 referenced by v1_demo is released.

1. Use global variables to reference class objects inside functions

>>> g_demo = None
>>> print(g_demo)
None
>>> 
>>> def return_gdemo():    
...     global g_demo
...     g_demo = demo()
... 
>>> 
>>> print(g_demo)
None
>>> return_gdemo()
init class
<__main__.demo instance at 0x7fc511eb8d88>
>>> 
>>> print(g_demo)
<__main__.demo instance at 0x7fc511eb8d88>
>>> 
>>> True
True
>>>
Copy after login

[Related recommendations: Python3 video tutorial]

The above is the detailed content of Detailed example of destruction and release of python class objects. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to efficiently integrate Node.js or Python services under LAMP architecture? How to efficiently integrate Node.js or Python services under LAMP architecture? Apr 01, 2025 pm 02:48 PM

Many website developers face the problem of integrating Node.js or Python services under the LAMP architecture: the existing LAMP (Linux Apache MySQL PHP) architecture website needs...

What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? Apr 01, 2025 pm 04:03 PM

When using Scapy crawler, the reason why pipeline persistent storage files cannot be written? Discussion When learning to use Scapy crawler for data crawler, you often encounter a...

What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? Apr 01, 2025 pm 04:09 PM

Python process pool handles concurrent TCP requests that cause client to get stuck. When using Python for network programming, it is crucial to efficiently handle concurrent TCP requests. ...

How to view the original functions encapsulated internally by Python functools.partial object? How to view the original functions encapsulated internally by Python functools.partial object? Apr 01, 2025 pm 04:15 PM

Deeply explore the viewing method of Python functools.partial object in functools.partial using Python...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

See all articles