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()
如您所见,上面的代码可以解释我的问题。
答案 0 :(得分:2)
您必须在Method:
中将指针存储回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)
如果您绝对需要避免在App中传递self
指针,则需要检查堆栈以检索它。
不建议使用以下内容,仅当您使用Method
方法实例化App
个对象时才有效:
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']