【问题标题】:Find which function is using a given class in python在python中查找哪个函数正在使用给定的类
【发布时间】:2021-08-31 04:17:03
【问题描述】:

我有课

class A:
 def __init__(self):
  print(i was used by :)

# if i call this class from the function below,
 
def my_func():
 a = A()

# I need class A to print that "i was used in: my_func() "

有什么解决办法吗?

【问题讨论】:

  • 最好将打印内容放在my_func 中作为print("my_func willl now be calling A")。或者,只需将函数名称作为A("my_func") 传递给A 的构造函数并使用它。
  • 我的意思是,也许是通过使用各种堆栈自省技巧。几乎可以肯定,您应该只要求将函数作为参数提供。
  • @NielGodfreyPonciano 我不知道哪个函数正在调用我的类。我需要弄清楚哪些功能可以。在我的代码中某处,一个类被我找不到的函数使用。

标签: python python-2.7


【解决方案1】:

如果你知道函数名:

你可以试试这样的:

class A:
    def __init__(self, func):
        print('i was used by:', func.__name__)

def my_func(func):
    a = A(func)
my_func(my_func)

输出:

i was used by: my_func

这里你可以指定函数实例,这是这里最优化的方式,然后只需使用__name__ 来获取函数的名称。

如果你不知道函数名:

你可以试试inspect 模块:

import inspect
class A:
    def __init__(self):
       print('i was used by:', inspect.currentframe().f_back.f_code.co_name)

def my_func():
    a = A()
my_func()

或者试试这个:

import inspect
class A:
    def __init__(self):
        cur = inspect.currentframe()
        a = inspect.getouterframes(cur, 2)[1][3]
        print('i was used by:', a)

def my_func():
    a = A()
my_func()

两个输出:

i was used by: my_func

【讨论】:

  • 谢谢,但我仍然不知道是哪个函数在调用我的类,我得到了大量的 Django 代码,我需要在其中找出 API 请求的触发位置。有一个类可以处理它,但我不知道从哪里使用它。
  • @cod4 编辑了我的答案,检查 Edit: 部分,这会起作用
  • 是的,这正是我想要的!
  • @cod4 欢迎您,添加了更短的版本,请随时查看:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2021-12-12
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-10-25
  • 2018-05-18
相关资源
最近更新 更多