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

标签 python python-2.7

我有课

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 - 在python中查找哪个函数正在使用给定的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68992807/

相关文章:

python - 如何将多个系列组合成一个选择单个非空值的系列?

Bash:将变量作为单个参数/shell 引用参数传递

python - 如何创建返回 `True` 的匿名函数?

python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?

python - 为什么 namedtuples 使用的内存比字典少?

python-2.7 - Python 2.7-Elasticsearch-SyntaxError:非ASCII字符 '\xc3'

python - 找不到套接字服务器的匹配发行版

python - OpenCV VideoWriter:播放视频的问题

python - 如何在 ubuntu 16.04 LTS 中安装 pip3 和 paramiko?

python - 将多个参数传递给 sys.stdout.write