添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
小猫猫  ·  问题解决:python2 ...·  1 周前    · 
逆袭的烈马  ·  dotnet dev-certs 命令 - ...·  10 月前    · 
善良的稀饭  ·  python ...·  1 年前    · 
霸气的麦片  ·  WebSocket获取httpSession ...·  1 年前    · 
使用 sys.getrefcount() 方法获取对象的引用计数,例如 sys.getrefcount(obj1) sys.getrefcount() 方法返回对象的引用计数。 该计数比预期高一,因为该方法创建了一个临时引用。

import sys obj1 = { 'id' : 1 , 'name' : 'jiyik' } print (sys.getrefcount(obj1)) # 👉️ 2 obj2 = obj1 print (sys.getrefcount(obj1)) # 👉️ 3 my_dict = { 'employee' : obj1, print (sys.getrefcount(obj1)) # 👉️ 4 sys.getrefcount() 方法返回所提供对象的引用计数。

计数比预期高一个,因为该方法创建了对所提供对象的临时引用。

import sys obj1 = { 'id' : 1 , 'name' : 'jiyik' } print (sys.getrefcount(obj1)) # 👉️ 2 如果需要获取直接引用给定对象的对象列表,可以使用 gc.get_referrers() 方法。

import sys import gc obj1 = { 'id' : 1 , 'name' : 'jiyik' } print (sys.getrefcount(obj1)) # 👉️ 2 # [{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10d34a910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/jiyik/workspace/python/study/main.py', '__cached__': None, 'sys': <module 'sys' (built-in)>, 'gc': <module 'gc' (built-in)>, 'obj1': {'id': 1, 'name': 'jiyik'}}] print (gc.get_referrers(obj1)) 第一个对象是当前命名空间,第二个是我们声明的变量。

gc.get_referrers() 方法返回直接引用所提供对象的对象列表。

我们可以使用 id 函数或 is 运算符来检查两个变量是否引用同一个对象。

import sys obj1 = { 'id' : 1 , 'name' : 'jiyik' } print (sys.getrefcount(obj1)) # 👉️ 2 obj2 = obj1 print (sys.getrefcount(obj1)) # 👉️ 3 print (obj1 is obj2) # 👉️ True print ( id (obj1)) # 👉️ 139709435242240 print ( id (obj2)) # 👉️ 139709435242240 print ( id (obj1) == id (obj2)) # 👉️ True 我们使用 del 运算符删除了 obj1 变量,因此 obj2 的引用计数减少到 2。

引用计数实际上是 1,但是 sys.getrefcount() 方法会创建对所提供对象的临时引用。

我们仍然可以通过 obj2 变量访问 obj1 的内容。

  • Python 错误 IsADirectoryError: [Errno 21] Is a directory 解决方法
  • 在 Python 中对元组列表进行排序
  • Python 错误 UnicodeDecodeError: 'utf-8' codec can't decode invalid continuation byte
  • Python从列表中随机选择N个元素
  • Python NameError: function is not defined 错误
  • Python 中 TypeError: Class() takes no arguments 错
  • Python 中 JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2
  • Python 打印不带括号的元组
  • 如何使用 Python 创建目录的 Zip 存档
  •