Python:如何在被调用的方法中获取调用者的方法名?
假设我有两种方法:
def method1(self):
...
a = A.method2()
def method2(self):
...
Run Code Online (Sandbox Code Playgroud)
如果我不想对method1进行任何更改,如何在method2中获取调用者的名称(在此示例中,名称为method1)?
是否可以装饰/扩展python标准日志记录系统,以便在调用日志记录方法时,它还会记录文件和调用它的行号,或者调用它的方法?
考虑以下python代码:
def function():
"Docstring"
name = ???
doc = ???
return name, doc
>>> function()
"function", "Docstring"
Run Code Online (Sandbox Code Playgroud)
我需要更换问号,以便从同一个函数中获取函数的名称和文档字符串?
编辑:到目前为止,大多数答案明确地硬编码其定义中的函数名称.是否可以执行类似下面的操作,其中新函数get_name_doc将从调用它的外框访问函数,并返回其名称和doc?
def get_name_doc():
???
def function():
"Docstring"
name, doc = get_name_doc()
return name, doc
>>> function()
"function", "Docstring"
Run Code Online (Sandbox Code Playgroud) 考虑以下伪代码:
func1():
func2() #func2 is called inside func1
Run Code Online (Sandbox Code Playgroud)
我的问题是,在func2中我可以访问它被调用的函数的名称吗?在这种情况下,func1?谢谢!
我有课
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() "
Run Code Online (Sandbox Code Playgroud)
有什么解决办法吗?