Python class 属性的生命周期

Lifetime of Python class attribute

class 属性在 Python 中的生命周期是多少?如果 class 当前没有实例存在,那么 class 及其 class 属性 可能会被垃圾收集,然后在class接下来用的是什么?

例如,考虑如下内容:

class C(object):
    l = []

    def append(self, x):
        l.append(x)

假设我创建了一个 C 的实例,将 5 附加到 C.l,然后 C 的那个实例不再被引用并且可以被垃圾收集。后来,我创建了另一个 C 的实例并读取了 C.l 的值。我能保证 C.l 会保持 [5] 吗?或者 class 本身及其 class 属性是否可能被垃圾收集,然后 C.l = [] 稍后执行第二次?

或者,换句话说:class属性的生命周期是"forever"吗? class 属性是否与全局变量具有相同的生命周期?

If no instances of the class are currently live, might the class and its class attributes be garbage-collected, and then created anew when the class is next used?

没有。没有 "next use" 的 class 被垃圾收集,因为它被垃圾收集的唯一方法是没有办法使用它。

Suppose I create an instance of C, append 5 to C.l, and then that instance of C is no longer referenced and can be garbage-collected. Later, I create another instance of C and read the value of C.l. Am I guaranteed C.l will hold [5]?

是的。 class 有一个实时引用,因为您创建了另一个实例,并且列表有一个实时引用作为 class 上的属性。

Does a class attribute have the same lifetime as a global variable?

如果 class 持有对某物的引用,则该某物将至少与 class 一样长。

你问了几个问题。

What's the lifetime of a class attribute, in Python?

class 属性只要有对它的引用就存在。由于 class 持有一个引用,它至少会与 class 存活一样长,假设 class 继续持有该引用。此外,由于每个对象都持有一个引用,因此它至少与所有对象一样长,假设每个对象继续持有引用。

Am I guaranteed C.l will hold [5]?

在你描述的假设中,是的。

Or is it possible that the class itself and its class attributes might get garbage-collected, and then C.l = [] executed a second time later?

没有假设您能够构建 C 的实例。如果您能够构造 C 的第二个实例,那么 C 必须存在,C.l

也必须存在

Is the lifetime of a class attribute "forever"?

没有。 class 属性的生命周期遵循任何对象的生命周期规则。只要对它的引用存在,它就存在。在C.l的情况下,class中存在一个引用,每个实例中都存在一个引用。如果你摧毁所有这些,那么 C.l 也会被摧毁。

Does a class attribute have the same lifetime as a global variable?

排序:class 属性存在,直到最后一个引用消失。全局变量也存在,直到最后一个引用消失。这些都不能保证持续整个程序的持续时间。

此外,在模块范围 定义的 class 是 全局变量。所以 class(并且,暗示,属性)在这种情况下与全局变量具有相同的生命周期。