我怎么能连接__call__实例?

时间:2012-07-18 10:48:01

标签: python

 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()

如您所见,上面的代码可以解释我的问题。

1 个答案:

答案 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']