python如何查看调用的函数_Python如何获取调用函数(不仅仅是它的名称)?

可以从任何代码对象(以及扩展模块/内置项)调用:从exec,execfile,从模块名称空间(导入期间),从类定义内,从方法/类方法/staticmethod中,从修饰函数/方法,从嵌套函数中。。。-所以总的来说没有“召唤功能”,而且很难用它做任何好事。在

堆栈帧及其代码对象是您可以获得并检查属性的最通用的。在

这个函数在很多情况下都可以找到调用函数:import sys, inspect

def get_calling_function():

"""finds the calling function in many decent cases."""

fr = sys._getframe(1) # inspect.stack()[1][0]

co = fr.f_code

for get in (

lambda:fr.f_globals[co.co_name],

lambda:getattr(fr.f_locals['self'], co.co_name),

lambda:getattr(fr.f_locals['cls'], co.co_name),

lambda:fr.f_back.f_locals[co.co_name], # nested

lambda:fr.f_back.f_locals['func'], # decorators

lambda:fr.f_back.f_locals['meth'],

lambda:fr.f_back.f_locals['f'],

):

try:

func = get()

except (KeyError, AttributeError):

pass

else:

if func.__code__ == co:

return func

raise AttributeError("func not found")

# Usage

def f():

def nested_func():

print get_calling_function()

print get_calling_function()

nested_func()

class Y:

def meth(self, a, b=10, c=11):

print get_calling_function()

class Z:

def methz(self):

print get_calling_function()

z = Z()

z.methz()

return z

@classmethod

def clsmeth(cls):

print get_calling_function()

@staticmethod

def staticmeth():

print get_calling_function()

f()

y = Y()

z = y.meth(7)

z.methz()

y.clsmeth()

##y.staticmeth() # would fail

它发现:

^{pr2}$

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值