简体   繁体   English

从python中的weakref代理获取常规引用

[英]Acquiring a regular reference from a weakref proxy in python

Is there a way to get a proper reference for an object for which I get a weakref proxy?有没有办法为我获得弱引用代理的对象获得正确的引用?

I've gone through the weakref module's documentation and coulnd't get an answer there, or through poking a weakproxy object manually.我已经浏览了weakref 模块的文档,但无法在那里得到答案,或者通过手动戳一个weakproxy 对象。

Although there's nothing exposed directly on the proxy object itself, it is possible to obtain a reference by abusing the __self__ attribute of bound methods:虽然代理对象本身没有直接暴露的东西,但可以通过滥用绑定方法的__self__属性来获取引用:

obj_ref = proxy.__repr__.__self__

Using __repr__ here is just a random choice, although if you want a generic method it'd be better to use a method that all objects should have.在此处使用__repr__只是一个随机选择,尽管如果您想要一个通用方法,最好使用所有对象都应具有的方法。

You can get the referent from a weakref object by calling it: 您可以通过调用它来从weakref对象获取引用:

obj = ref()

From the weakref docs : 来自weakref文档

Weak reference objects have no attributes or methods, but do allow the referent to be obtained, if it still exists, by calling it. 弱引用对象没有属性或方法,但如果它仍然存在,则允许通过调用它来获取引用对象。 If the referent no longer exists, calling the reference object returns None . 如果引用对象不再存在,则调用引用对象将返回None

This doesn't work for proxy objects though, and I don't see a way to get to a weak reference object or a reference to the actual object from a weakref proxy. 这对代理对象不起作用,我没有看到从weakref代理获取弱引用对象或对实际对象的引用的方法。

I don't know what you mean by a proper reference, but according to: https://pymotw.com/2/weakref/ ,我不知道您所说的正确参考是什么意思,但根据: https : //pymotw.com/2/weakref/

you can just use the proxy as if you would use the original object.您可以像使用原始对象一样使用代理。

import weakref

class ExpensiveObject(object):
    def __init__(self, name):
        self.name = name
    def __del__(self):
        print '(Deleting %s)' % self

obj = ExpensiveObject('My Object')
r = weakref.ref(obj)
p = weakref.proxy(obj)

print 'via obj:', obj.name
print 'via ref:', r().name
print 'via proxy:', p.name
del obj
print 'via proxy:', p.name

This contrasts to using weakref.ref, where you have to call, ie use the ()-operator on, the weak reference to get to the original object.这与使用weakref.ref 形成对比,在那里您必须调用,即在弱引用上使用() 运算符来获取原始对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM