Python class methods __init__ and __del__ construction and destructor analysis

self.__class__ accesses the class itself, and then accesses its own shared member variables, namely self.__class__.num_count, 
Replace NewClass.num_count in the class with self.__class__.num_count Compile and run



This article mainly introduces the Python class methods __init__ and __del__ construction and analysis of the destructor process. This article analyzes when to construct, when to destruct, how to deal with member variables, and how to access shared member functions in Python. , friends who need it can refer to the following

Recently I learned the Class part of the "Python Reference Manual" and encountered the problem of the construction and destructor part of the class:

1. When is it constructed?
2. When is it destructed?
3. How to deal with member variables?
4. How to access shared member functions in Python?
------------------------
Exploration process:
1. After searching, there is no dedicated constructor and destructor in Python, but it can generally be found in __init__ and __del__ to complete initialization and deletion operations, respectively, can be used instead of construction and destructor. There is also a __new__ used to customize the class creation process, but it requires certain configuration, which will not be discussed here. 
2. The member functions of a class are equivalent to public by default, but the default starting with __ is a private variable. Although it is private, we can still access it by certain means, that is, there is no real private variable in Python. Such as:

copy code code show as below:

__priValue = 0 # Will be automatically transformed into a member variable of "_class name __priValue"

3. Due to the particularity of Python, global member variables are shared, so the instance of the class will not allocate content space for it, similar to static. For details, see the following example.

Test 1:

copy code code show as below:

# encoding:utf8

class NewClass(object):
    num_count = 0 # 所有的实例都共享此变量,即不单独为每个实例分配
    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"

调试运行:

复制代码代码如下:

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

我们发现,num_count 是全局的,当每创建一个实例,__init__()被调用,num_count 的值增一,当程序结束后,所有的实例会被析构,即调用__del__() 但是此时引发了异常。查看异常为 “NoneType” 即 析构时NewClass 已经被垃圾回收,所以会产生这样的异常。

但是,疑问来了?为什么会这样?按照C/C++等语言的经验,不应该这样啊!经过查找资料,发现:

Python的垃圾回收过程与常用语言的不一样,Python按照字典顺序进行垃圾回收,而不是按照创建顺序进行。所以当系统进行回收资源时,会按照类名A-Za-z的顺序,依次进行,我们无法掌控这里的流程。

明白这些,我们做如下尝试:

复制代码代码如下:

# encoding:utf8

class NewClass(object):
    num_count = 0 # 所有的实例都共享此变量,即不单独为每个实例分配
    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"

调试输出:

复制代码代码如下:

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

OK,一切按照我们预料的顺序发生。
但是,我们总不能每次都手动回收吧?这么做Python自己的垃圾回收还有什么意义?

SO,继续查找,我们还可以通过self.__class__访问到类本身,然后再访问自身的共享成员变量,即 self.__class__.num_count , 将类中的NewClass.num_count替换为self.__class__.num_count 编译运行,如下:

复制代码代码如下:

# encoding:utf8

class NewClass(object):
    num_count = 0 # 所有的实例都共享此变量,即不单独为每个实例分配
    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"

结果:

复制代码代码如下:

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

Perfect!我们完美地处理了这个问题!

PS:

书上又提到了一些问题,在这里作补充(仅作为参考):

__new__()是唯一在实例创建之前执行的方法,一般用在定义元类时使用。

del xxx 不会主动调用__del__方法,只有引用计数==0时,__del__()才会被执行,并且定义了__del_()的实例无法被Python的循环垃圾收集器收集,所以尽量不要自定义__del__()。一般情况下,__del__() 不会破坏垃圾处理器。

实验中发现垃圾回收自动调用了__del__, 这与书上所说又不符,不知是什么原因,需要继续学习。


出处:http://www.jb51.net/article/61831.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325916816&siteId=291194637