Python class method _ init _ and _ del _ structure and structure process analysis, __init ___ del _
I recently learned the Class part in the Python reference manual and encountered the problem of constructing the Class structure:
1. When to construct the SDK?
2. When to analyze the structure?
3. How to Deal with member variables?
4. How do I access Shared member functions in Python?
------------------------
Exploration process:
1. After searching, Python does not have dedicated constructor and destructor. However, you can initialize and delete them in _ init _ and _ del _ respectively, this can be used to replace the construction and analysis structure. There is also a _ new _ process used to create a custom class, but some configuration is required. We will not discuss it here.
2. The member functions of the class are equivalent to public by default, but the default start with _ is a private variable. Although it is private, it can be accessed through some means, that is, Python does not have real private variables. For example:
Copy codeThe Code is as follows:
_ PriValue = 0 # The member variable "_ class name__ priValue" is automatically deformed.
3. Due to the special nature of Python, global member variables are shared, so the class instance will not allocate content space for it, similar to static. For more information, see the example below.
Test 1:
Copy codeThe Code is as follows:
# Encoding: utf8
Class NewClass (object ):
Num_count = 0 # all instances share this variable, that is, they are not allocated to each instance separately.
Def _ init _ (self, name ):
Self. name = name
NewClass. num_count + = 1
Print name, NewClass. num_count
Def _ del _ (self ):
NewClass. num_count-= 1
Print "Del", self. name, NewClass. num_count
Def test ():
Print "aa"
Aa = NewClass ("Hello ")
Bb = NewClass ("World ")
Cc = NewClass ("aaaa ")
Print "Over"
Debug and run:
Copy codeThe Code is as follows:
Hello 1
World 2
Aaaa 3
Over
DeException l Hello 2
AttributeError: "'nonetype 'object has no attribute 'num _ count'" in <bound method NewClass. _ del _ of <__ main __. newClass object at 0x01AF18D0> ignored
Exception AttributeError: "'nonetype 'object has no attribute 'num _ count'" in <bound method NewClass. _ del _ of <__ main __. newClass object at 0x01AF1970> ignored
We found that num_count is global. When every instance created __init _ () is called, the value of num_count is increased by one. When the program ends, all instances will be destructed, namely calling _ del _ (), but an exception is thrown. Check that the exception is "NoneType", that is, NewClass has been garbage collected during the destructor, so this exception will occur.
But is there a question? Why? According to the experience in C/C ++ and other languages, this should not be the case! After searching for information, we found that:
The garbage collection process of Python is different from that of common languages. Python garbage collection is performed in alphabetical order, rather than in the creation order. So when the system recycles resources, it will follow the class name A-Za-z in sequence, and we cannot control the process here.
To understand this, let's try the following:
Copy codeThe Code is as follows:
# Encoding: utf8
Class NewClass (object ):
Num_count = 0 # all instances share this variable, that is, they are not allocated to each instance separately.
Def _ init _ (self, name ):
Self. name = name
NewClass. num_count + = 1
Print name, NewClass. num_count
Def _ del _ (self ):
NewClass. num_count-= 1
Print "Del", self. name, NewClass. num_count
Def test ():
Print "aa"
Aa = NewClass ("Hello ")
Bb = NewClass ("World ")
Cc = NewClass ("aaaa ")
Del aa
Del bb
Del cc
Print "Over"
Debugging output:
Copy codeThe Code is as follows:
Hello 1
World 2
Aaaa 3
Del Hello 2
Del World 1
Del aaaa 0
Over
Okay. Everything happens in the expected order.
However, we cannot manually recycle them every time, right? What is the significance of Python garbage collection?
SO, continue to search, we can also use self. _ class _ accesses the class itself, and then accesses its own shared member variable, that is, self. _ class __. num_count: NewClass in the class. replace num_count with self. _ class __. num_count:
Copy codeThe Code is as follows:
# Encoding: utf8
Class NewClass (object ):
Num_count = 0 # all instances share this variable, that is, they are not allocated to each instance separately.
Def _ init _ (self, name ):
Self. name = name
Self. _ class _. num_count + = 1
Print name, NewClass. num_count
Def _ del _ (self ):
Self. _ class _. num_count-= 1
Print "Del", self. name, self. _ class _. num_count
Def test ():
Print "aa"
Aa = NewClass ("Hello ")
Bb = NewClass ("World ")
Cc = NewClass ("aaaa ")
Print "Over"
Result:
Copy codeThe Code is as follows:
Hello 1
World 2
Aaaa 3
Over
Del Hello 2
Del World 1
Del aaaa 0
Perfect! We handled this problem perfectly!
PS:
I have mentioned some problems in the book. I will add them here (for reference only ):
_ New _ () is the only method that is executed before the instance is created. It is generally used to define metadata.
Del xxx does not actively call the _ del _ method. Only when the reference count is = 0, __del _ () is executed and _ del _ () is defined _() the instance cannot be collected by Python's garbage collector, so do not customize _ del __(). Generally, __del _ () does not destroy the spam processor.
In the experiment, we found that garbage collection automatically called _ del __, which is inconsistent with what we mentioned in the book. I don't know why, so I need to continue learning.