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

时间:2018-07-31 17:00:47

标签: python python-3.x

来自documentation

  
    

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?

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:2)

您正在使用IPython,它具有自己的漂亮打印工具。 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__属于其类,因此漂亮打印机认为代理确实是ExpensiveObject的实例。它看不到代理的__repr__,并且将类打印为ExpensiveObject而不是weakproxy

答案 1 :(得分:0)

有些奇怪,因为我无法重现您的问题:

>>> import weakref
>>> class Foo: pass
... 
>>> f = Foo()
>>> f
<__main__.Foo object at 0x7f40c44f63c8>
>>> p = weakref.proxy(f)
>>> p
<weakproxy at 0x7f40c44f9a98 to Foo at 0x7f40c44f63c8>
>>> r = weakref.ref(f)
>>> r
<weakref at 0x7f40c4502278; to 'Foo' at 0x7f40c44f63c8>
>>> r()
<__main__.Foo object at 0x7f40c44f63c8>

此代码已在新的解释程序实例中输入。输出与您的输出有很大不同!您使用的是哪个版本的python?