python从字符串解析方法名

  方法以下函数

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

若是是当前文件的方法ui

test.pyspa

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

这个的用处是code

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

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

查看getattr的doc,blog

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的对象(类对象或者函数对象)。字符串

相关文章
相关标签/搜索