【问题标题】:Why there are three references to the class attribute?为什么对类属性有三个引用?
【发布时间】:2020-04-09 22:41:18
【问题描述】:

让我们考虑这段代码:

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 返回一个空列表?

【问题讨论】:

    标签: python-3.x class-attributes


    【解决方案1】:

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

    sys.getrefcount(object): 返回对象的引用计数。返回的计数通常比您预期的高 1,因为它包含(临时)引用作为 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):返回任何参数直接引用的对象列表。[...]

    gc.get_referrers(*objs): 返回直接引用任何 objs 的对象列表。 [...]

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 2023-03-05
      • 2022-01-16
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多