我想获取有关 python 中特定函数的调用者的信息。例如:
class SomeClass():
def __init__(self, x):
self.x = x
def caller(self):
return special_func(self.x)
def special_func(x):
print "My caller is the 'caller' function in an 'SomeClass' class."
用python可以吗?
是的sys._getframe()函数让您从当前执行堆栈中检索帧,然后您可以使用在inspect module;您将在以下地区寻找特定的当地人f_locals
属性,以及对于f_code
信息:
import sys
def special_func(x):
callingframe = sys._getframe(1)
print 'My caller is the %r function in a %r class' % (
callingframe.f_code.co_name,
callingframe.f_locals['self'].__class__.__name__)
请注意,您需要小心检测在每个帧中找到的信息类型。
sys._getframe()
返回一个框架对象,您可以通过以下方式链接整个堆栈f_back
各有参考。或者您可以使用inspect.stack()功能生成带有附加信息的帧列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)