Python - 我可以访问调用我的对象吗?
如果我有这样的想法:
class A:
def callFunction(self, obj):
obj.otherFunction()
class B:
def callFunction(self, obj):
obj.otherFunction()
class C:
def otherFunction(self):
# here I wan't to have acces to the instance of A or B who call me.
...
# in main or other object (not matter where)
a = A()
b = B()
c = C()
a.callFunction(c) # How 'c' know that is called by an instance of A...
b.callFunction(c) # ... or B
尽管存在设计或其他问题,但这只是一个好奇心的问题。
注意:这必须在不更改的情况下完成 otherFunction
签名
If I have this:
class A:
def callFunction(self, obj):
obj.otherFunction()
class B:
def callFunction(self, obj):
obj.otherFunction()
class C:
def otherFunction(self):
# here I wan't to have acces to the instance of A or B who call me.
...
# in main or other object (not matter where)
a = A()
b = B()
c = C()
a.callFunction(c) # How 'c' know that is called by an instance of A...
b.callFunction(c) # ... or B
Despite the design or other issues, this is only a question of an inquiring mind.
Note: This has to be done without changing otherFunction
signature
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果这是出于调试目的,您可以使用inspect.currentframe():
以下是输出:
If this is for debugging purposes you can use inspect.currentframe():
Here is the output:
这是一个快速技巧,获取堆栈并从最后一帧获取局部变量以访问自身
输出:
Here is a quick hack, get the stack and from last frame get locals to access self
output:
使用 inspect 模块 和
inspect 检查堆栈.stack()。然后,您可以使用
f_locals['self']
从列表中的每个元素获取实例Examine the stack with the inspect module with
inspect.stack()
. You can then get the instance from each element in the list withf_locals['self']