python从字符串解析方法名

  方法如下

import requests
func_name = 'get'
fn_obj = getattr(requests,func_name)
fn_obj('http://www.baidu.com')

如果是当前文件的方法

test.py

import sys
def fn():
    print('hello world')
func_name = fn.__name__
fn_obj = getattr(sys.modules[__name__], func_name)
            # 根据函数名(func_name),获得函数对象
fn_obj()
            # hello world

这个的用处是

有时我们需要将一个文件的信息(类、函数及变量)保存到文件,我们不能直接保存函数对象,而是将其转化为fn.__name__,问题来了,当我们想通过读取文件的形式重新配置这些类、函数时,该如何把这些字符串转换为对应的函数对象呢?

print(sys.modules[__name__])
    # <module '__main__' from '**/test.py'>

查看getattr的doc,

getattr(object, name[, default]) -> value. Get a named attribute from an object; getattr(x, ‘y’) is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn’t exist; without it, an exception is raised in that case.

所以,getattr(sys.modules[__name__], func_name)的含义便是找到当前文件下名称为func_name的对象(类对象或者函数对象)。

posted @ 2018-05-15 10:33  巫谢  阅读(2002)  评论(0编辑  收藏  举报