我有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