What is the life cycle of functions and classes in Python?

The function in

Python is an instance of function , while a class is an instance of type , so what is the life cycle of the function and class?

In [1]: def func():
   ...:     pass
   ...:

In [2]: type(func)
Out[2]: function

In [3]: class Test(object):
   ...:     pass
   ...:

In [4]: type(Test)
Out[4]: type
Is

created and survived until the end of the program, or is it calculated by reference count?

if it is calculated by reference count, how is the reference count of functions and classes calculated?

Mar.28,2021

of course, there is still reference counting. If the count is not returned to zero, it will not be recycled. The function is an instance of function , and the class is an instance of type . Understand def func () as func = new Function () , when the function instance count is 1. If you delete its reference del func or assign other values to func , causing the function object reference count to be 0, then it will be recycled. In the same way, class Test (object) is regarded as Test = new type () , and its reference count is the same as ordinary variable calculation, nothing special. So as long as the reference count is not zero, its life cycle is the life cycle of the entire program.

at this point, del operations are performed at the end of the text for functions or classes in the module that are not exposed to the user's privacy, such as datetime.py in the standard library.


that depends on where you define it

if you define global, that is the entire program life cycle; if defined in a subblock such as if for, it is valid in the local scope of that subblock unless referenced by other scopes

Menu