在 python 中查找哪个函数正在使用给定的 class

Find which function is using a given class in python

我有class

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() "

有解决办法吗?

如果你知道函数名:

您可以尝试类似的方法:

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