简体   繁体   中英

Why does Python destroy class variables before objects?

I understand that Python doesn't guarantee the order of destruction of objects at the end of the program, or even that it will happen.

So I understand that a class's destructor can't rely on global variables, including other modules.

But I would have thought that objects of the class would have to be destroyed before the class is destroyed. Apparently not:

class A(object):
    count = 0
    def __init__(self):
        A.count += 1
        print 'Creating object, there are now', A.count
    def __del__(self):
        A.count -= 1
        print 'Destroying object, there are now', A.count

a1 = A()
a2 = A()

On Windows 7 x64 Python v2.7.3 I get:

Creating object, there are now 1
Creating object, there are now 2
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
 method A.__del__ of <__main__.A object at 0x0234B8B0>> ignored
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
 method A.__del__ of <__main__.A object at 0x0234BE90>> ignored

I understand the implications of How do I correctly clean up a Python object? . But this case is for class (shared or 'static' for my C++ friends) variables. Surely the instance has a reference to the class variable, which should not be destroyed first as we still have a reference to it?

Is it a problem or a mistake to have the class destroyed before objects of that class? Maybe my question is 'Where are class-shared variables actually stored?"

(Yes, I understand that this can be rectified using a context manager, or even simply:

del a1
del a2

to destroy the object before the class is destroyed.)

Maybe my question is 'Where are class-shared variables actually stored?"

If that is your question, the answer is "on the class".

To address your larger question: As you noted, __del__ can't rely on global variables — but A is a global variable, so you can't rely on it. Interestingly, I can't find an official statement of this in the docs, but there are various references on the internet to this fact that __del__ can't use global variables. Here is one:

When a Python program terminates the global variables in each module are set to None. The order in which this happens it undefined

It will work if you access the count via self.__class__.count instead of A.count . (This is also why it works when you use self.count .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM