python - weakref.proxy 和 weakref.ref 之间的区别?

标签 python python-3.x

来自 documentation :

Weakref.proxy returns a proxy to object which uses a weak reference. But if I run the following code:

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,它有自己的 pretty-print 工具。 default pretty-printer更喜欢通过 __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__ 隐藏了它们的类,因此 pretty-print 认为代理确实是 ExpensiveObject 的一个实例.它看不到代理的 __repr__,并将类打印为 ExpensiveObject 而不是 weakproxy

关于python - weakref.proxy 和 weakref.ref 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618579/

相关文章:

python - Py.test 修补模块内对象

python - 用 python 中的另一个列表迭代列表列表

python : special char to binary

python - Tornado 处理程序在 python 中 fork 额外的工作

python-3.x - 将 BigQuery 表导出到 Google 存储时如何避免 header

Python子类调用父类的方法

python - 从管理界面上传新音频文件时,django-audiofield没有此类文件或目录

Python SQL 插入语句不起作用

python-3.x - 使用 OpenCV 比较两个图像

python - 替换子列表中的项目而不展平