python - 获取调用方法的对象

标签 python python-3.x

我需要获取调用另一个函数的对象方法。我不想要它的名字,而是实际的对象。

到目前为止,我已经明白了。

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/

相关文章:

python - 用于分类变量的 Scikit-learn DictVectorizer

python - Tkinter 框架暂停程序。程序不会继续,直到我关闭框架

python - 导入后使全局范围内的变量可供类使用

python - 动态规划背包 K-精确项目

jquery - 将数据传递到后端的传统方法?

python - 故障排除 "descriptor ' 日期'需要 'datetime.datetime' 对象,但收到 'int'“

python-3.x - pkg_resources.resource_filename 未提取文件

python - 为什么 tkinter.ttk Combobox 仅在初始选择时清除显示值?

python - bisect_left 在列表中列表的第一项上,Python 3

python - 日期时间模块中异常消息的来源。值错误: year 10000 is out of range