我需要获取调用另一个函数的对象方法。我不想要它的名字,而是实际的对象。
到目前为止,我已经明白了。
import inspect
def info():
stack_call = inspect.stack()
cls_method = stack_call[1][3]
cls_obj = stack_call[1].frame.f_locals["self"]
cls_members = inspect.getmembers(cls_obj)
my_obj = None
for el in cls_members:
if el[0] == cls_method:
my_obj = el[1]
break
print(my_obj)
class Bob:
def __int__(self):
pass
def jim(self):
info()
test = Bob()
test.jim()
它做了我想做的事情,但我不喜欢必须浏览列表才能找到正确的方法及其名称。
我尝试了很多方法,但不知道如何让它变得更好。
有人有更好的版本吗?
最佳答案
有点不同:
def info():
stack_call = inspect.stack()
cls_obj = stack_call[1].frame.f_locals[list(stack_call[1].frame.f_locals.keys())[0]]
cls_method = getattr(cls_obj, stack_call[1][3])
print(cls_method)
关于python - 获取调用方法的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097618/