实现说明
逻辑集中在类 Session和函数 __init__里。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 __init__。
主签名形如 def __init__(self, user)
核心语句
def __init__(self, user):
self.user = user
代码示例
import weakref
class Session:
def __init__(self, user):
self.user = user
# WeakValueDictionary 的值是弱引用:没人再持有 Session 时条目自动消失
cache = weakref.WeakValueDictionary()
sess = Session('alice')
cache['alice'] = sess
print('stored :', 'alice' in cache)
# 删除最后一个强引用:CPython 引用计数立即回收(无循环引用时),条目跟着消失
del sess
print('after del :', 'alice' in cache, len(cache))
# 强引用保留期间条目稳定存在
keeper = Session('bob')
cache['bob'] = keeper
print('kept :', cache['bob'].user)
# 运行时仍是 dict 语义:get/默认值照常工作
print('missing :', cache.get('carol', 'no session'))