Python类attribu的生存期

2024-06-26 17:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,类属性的生存期是多少?如果当前没有类的实例处于活动状态,是否可以对该类及其类属性进行垃圾收集,然后在下次使用该类时重新创建该类?

例如,考虑如下内容:

class C(object):
    l = []

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

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

或者,换一种说法:类的生存期是属性“forever”吗?类属性是否与全局变量具有相同的生存期?


Tags: 实例self内容属性objectdefclass垃圾
2条回答

你问了几个问题。在

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

只要有对类属性的引用,类属性就会一直存在。因为类持有一个引用,所以假设类继续持有引用,它将至少和类的生命一样长。另外,由于每个对象都有一个引用,所以它至少和所有对象一样长,假设每个对象都继续保持引用。在

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"?

不,类属性的生存期遵循任何对象的生存期规则。只要对它的引用存在,它就存在。在C.l的情况下,类中存在一个引用,每个实例中都存在一个引用。如果你销毁了所有这些,那么{}也将被销毁。在

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

在最后一个引用消失之前,类属性一直存在。全局变量也存在,直到最后一个引用消失。这两种方法都不能保证在整个项目期间持续。在

同样,在模块作用域定义的类是一个全局变量。因此,在这种情况下,类(以及属性)与全局变量具有相同的生存期。在

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?

不,已经被垃圾回收的类不存在“下一次使用”的情况,因为垃圾回收的唯一方法是如果没有办法使用它。在

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]?

是的。该类有一个活动引用,因为您创建了另一个实例,而该列表将一个活动引用作为类的属性。在

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

如果类包含对某个对象的引用,则该类的生存期至少与该类相同。在

相关问题 更多 >