gpt4 book ai didi

python - 我怎样才能附加 __call__ 实例?

转载 作者:行者123 更新时间:2023-12-01 05:58:25 43 4
gpt4 key购买 nike

 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)

如果您绝对需要避免在 App 中传递 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']

关于python - 我怎样才能附加 __call__ 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539632/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com