python - weakref.proxy 和weakref.ref 之间的区别?
问题描述
从文档中:
Weakref.proxy 返回一个使用弱引用的对象的代理。但是,如果我运行以下代码:
obj = SomeObj()
obj # <__main__.ExpensiveObject at 0xbfc5390>
p = weakref.proxy(obj)
r = weakref.ref(obj)
r() # <__main__.ExpensiveObject at 0xbfc5390>
# the weakreference gives me the same object as expected
p # <__main__.ExpensiveObject at 0xc456098>
# the proxy refers to a different object, why is that?
任何帮助将不胜感激!谢谢!
解决方案
您正在使用 IPython,它有自己的漂亮打印工具。默认的漂亮打印机更喜欢通过__class__
而不是检查对象的类type
:
def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = _safe_getattr(obj, '__class__', None) or type(obj)
if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
# A user-provided repr. Find newlines and replace them with p.break_()
_repr_pprint(obj, p, cycle)
return
p.begin_group(1, '<')
p.pretty(klass)
...
但是weakref.proxy
对象通过 谎称他们的类__class__
,所以漂亮的打印机认为代理确实是 的一个实例ExpensiveObject
。它看不到代理的__repr__
,并将类打印为ExpensiveObject
而不是weakproxy
。
推荐阅读
- python - 在python中将XML转换为字典列表
- php - PHP 7.2 Apache not executing all php code
- c# - 当 LINQ 应该影响链中的先前调用时,它是如何工作的?(例如 mongo/Linq2Sql)
- python - Twilio 上的失败消息
- c++ - C++ 中的对象初始化语法( T obj = {...} vs T obj{...} )
- pandas-groupby - 熊猫群比;计算重叠列
- swift - 是否可以从 iOS 读取 QR 码的纠错值?
- wordpress - Woocommerce过滤器类别VS标签VS属性,什么时候用什么?
- python - 减法列表不起作用。我减去所有其他元素
- python - 如何让 pyaudio 从一个扬声器中播放