我需要获取调用另一个函数的对象方法。我不想要它的名字,我想要的是实际的对象。
到目前为止,我做到了这一点。
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()它做了我想做的事情,但我不喜欢必须遍历列表才能找到正确的方法及其名称。
我试过很多方法,但都不知道怎么做才好。
有人会有更好的版本吗?
发布于 2019-08-30 03:51:17
有一点不同:
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)https://stackoverflow.com/questions/57097618
复制相似问题