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()
如您所见,上面的代码可以解释我的问题。
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()
如您所见,上面的代码可以解释我的问题。
您必须将指针存储回方法中的 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
在以下方法中实例化对象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']