class Method(object):
def __call__(self):
#how could I get the App instance here?
return True
class App(object):
def __init__(self):
self.g = Method()
正如你所看到的,上面的代碼可以解釋我的問題。如何獲得__call__實例的附件?
class Method(object):
def __call__(self):
#how could I get the App instance here?
return True
class App(object):
def __init__(self):
self.g = Method()
正如你所看到的,上面的代碼可以解釋我的問題。如何獲得__call__實例的附件?
你不得不存儲指針回App對象的方法:
class Method(object):
def __init__(self, app):
self.app = app
def __call__(self):
self.app.something()
return True
class App(object):
def __init__(self):
self.g = Method(self)
如果你有絕對的必要,以避免傳遞self
指針在應用程序,你需要檢查堆棧來取代它。
以下是氣餒,只有當你在App
方法實例化對象Method
工作:
import sys
class Method(object):
def __init__(self):
parent = sys._getframe(1) # Calling context
locals_ = frame.f_locals
assert ('self' in locals_,
'Method objects can only be instanciated inside instance methods')
self.app = locals_['self']
這將爲每個實例創建一個類似於「綁定方法」的內容。爲此使用描述符可能會更好,所以我們只需要一個類的實例,並且只在必要時才創建「綁定方法」。我正在等待OP對我評論的回答。 – 2012-07-18 10:53:32
@SvenMarnach:我同意,但對於用例可能太複雜了。像往常一樣,背景太少。 – 2012-07-18 10:56:25
我可以不通過應用程序實例嗎? – Dreampuf 2012-07-18 11:00:33
什麼是'self'中應該指的是最後一行? – 2012-07-18 10:49:45
@SvenMarnach對不起我的錯誤。我已經更新了這個問題。 – Dreampuf 2012-07-18 11:02:37
你能解釋一下你想達到的目標嗎?問題的背景太少,無法說出最佳選擇。 – 2012-07-18 11:05:59