为什么对 class 属性有三个引用?

Why there are three references to the class attribute?

让我们考虑这段代码:

import sys
import gc

class A:
    a = "something here to print"
    def __init__(self):
        pass

a = A()
print(sys.getrefcount(A.a))  # prints 3


refs = gc.get_referents(A.a)
print(len(refs))             # prints 0

我不明白为什么打印3。第三个引用在哪里?

为什么 gc.get_referents returns 是一个空列表?

sys 的文档回答了您问题的第一部分:

sys.getrefcount(object): Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

考虑这个问题的第二部分:

import sys
import gc


class A:
    a = "something here to print"
    def __init__(self):
        pass

a = A()
print(sys.getrefcount(A.a))     # prints 3

refs = gc.get_referents(A.a)
print(len(refs))                # prints 0

refs2 = gc.get_referrers(A.a)   # prints 2 (what you expected)
print(len(refs2))

参见两种 gc 方法的文档:

gc.get_referents(*objs): Return a list of objects directly referred to by any of the arguments.[...]

gc.get_referrers(*objs): Return the list of objects that directly refer to any of objs. [...]