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

我有课

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

以上是在python中查找哪个函数正在使用给定的类的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>