我發現this recipe創建一個代理類。我用它來包裝自定義對象,並且想要重載某些屬性並將新屬性附加到代理上。然而,當我在代理上調用任何方法時(從代理類中),我最終被委託給了不是我想要的包裝。Python對象代理:如何訪問代理
有什麼方法可以訪問或存儲對代理的引用嗎?
下面是一些代碼(未經測試)來演示問題。
class MyObject(object):
@property
def value(self):
return 42
class MyObjectProxy(Proxy): # see the link above
def __getattribute__(self, attr):
# the problem is that `self` refers to the proxied
# object and thus this throws an AttributeError. How
# can I reference MyObjectProxy.another_value()?
if attr == 'value': return self.another_value() # return method or attribute, doesn't matter (same effect)
return super(MyObjectProxy, self).__getattribute__(attr)
def another_value(self):
return 21
o = MyObject()
p = MyObjectProxy(o)
print o.value
print p.value
從某種意義上說我的問題是,代理工作太出色了,隱藏所有自己的方法/屬性,並冒充自己作爲代理對象(這是它應該做的)...
更新
基於下面的評論,我改變__getattribute__
這樣:
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
return super(MyObjectProxy, self).__getattribute__(attr)
這看ms現在就可以完成這個技巧,但最好直接添加到Proxy
類中。
感謝您的再現和確認,@張揚餘。有關如何獲得所需行爲的任何建議? – orange
我已經更新了我的答案。請檢查。 @orange – zhangyangyu
我以爲我曾嘗試過,但我一定犯了一個錯誤。你的解決方案工作正常在查看代理人的代碼之前,我先看看如何修改代理類來查找自己的屬性。 – orange