Python-class method __init__ and __del__ structure, destructor analysis _python

Source: Internet
Author: User
Tags garbage collection

A recent study of the Python reference manual has learned the class section and encountered problems with the structural destructor of the class:

1. When is the construction?
2. When is the destructor?
3, the member variable how to deal with?
4. How do shared member functions in Python be accessed?
------------------------
Explore the process:
1, after looking, Python does not have a dedicated construction and destructor, but generally can be completed in __init__ and __del__ respectively initialization and deletion operations, can be used to replace the structure and destructor. There is also a __new__ used to customize the creation of the class, but a certain configuration is required, not discussed here.
2, the member function of the class is the default is public, but the default start is __ The private variable, although it is private, but we can also access through a certain means, that Python does not exist real private variables. Such as:

Copy Code code as follows:

__privalue = 0 # will automatically deform to "_ Class name __privalue" member variable

3. Because of the specificity of Python, global member variables are shared, so instances of the class do not allocate content space specifically for it, similar to static, using the example below.

Test 1:

Copy Code code as follows:

# Encoding:utf8

Class Newclass (object):
Num_count = 0 # All instances share this variable, that is, not individually allocated for each instance
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 Run:

Copy Code code 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 <__m ain__. Newclass object at 0x01af1970>> ignored

We find that Num_count is global, and when each instance is created, __init__ () is invoked, the value of Num_count is added, and when the program is finished, all instances are refactored, that is, __del__ (), but the exception is thrown. This exception is generated when viewing the exception as "Nonetype", which is the newclass that was garbage collected when the destructor occurred.

But is the question coming? Why is that? In accordance with the experience of C + + and other languages, should not be so ah! After searching the data, we found that:

Python's garbage collection process is not the same as a common language, and Python is garbage collected in dictionary order rather than in the order in which it was created. So when the system is recycling resources, according to the order of the class name a-za-z, we can not control the process here.

To understand these, we try to do the following:

Copy Code code as follows:

# Encoding:utf8

Class Newclass (object):
Num_count = 0 # All instances share this variable, that is, not individually allocated for each instance
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"

Debug output:

Copy Code code as follows:

Hello 1
World 2
AAAA 3
Del Hello 2
Del World 1
Del AAAA 0
Over

OK, everything happens in the order we expected.
However, we can not always manually recycle it? What's the point of doing Python's own garbage collection?

So, continue to find, we can also access to the class itself through self.__class__, and then access its own shared member variables, that is, Self.__class__.num_count, replace the Newclass.num_count in the class with self.__ Class__.num_count compiled to run as follows:

Copy Code code as follows:

# Encoding:utf8

Class Newclass (object):
Num_count = 0 # All instances share this variable, that is, not individually allocated for each instance
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"

Results:

Copy Code code as follows:

Hello 1
World 2
AAAA 3
Over
Del Hello 2
Del World 1
Del AAAA 0

perfect! We handled the problem perfectly!

Ps:

A number of questions are mentioned in the book, supplemented here (for reference only):

__new__ () is the only method that is executed before the instance is created, and is generally used when defining the Meta class.

del XXX does not actively invoke the __del__ method, and the __del__ () is executed only when the reference count ==0, and the instance that defines __del_ () is not collected by the Python recycle garbage collector, so try not to customize __del__ (). In general, __del__ () does not destroy the garbage processor.

The experiment found that garbage collection automatically called the __del__, which is inconsistent with the book said, I do not know what the reason, need to continue to learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.