首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >weakref.proxy和weakref.ref的区别是什么?

weakref.proxy和weakref.ref的区别是什么?
EN

Stack Overflow用户
提问于 2018-08-01 01:00:47
回答 2查看 1.3K关注 0票数 2

documentation

Weakref.proxy返回使用弱引用的object的代理。但是如果我运行以下代码:

代码语言:javascript
复制
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?

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-01 03:45:12

您使用的是IPython,它有自己漂亮的打印工具。default pretty-printer更喜欢通过__class__而不是type来检查对象的类

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2018-08-01 01:04:52

有些事情很奇怪,因为我不能重现你的问题:

代码语言:javascript
复制
>>> 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?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51618579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档