sys.modules[__name__]

A way to get a handle to the current running module in Python:
import sys
module = sys.modules[__name__]
it really only works if you are doing the whole sys.modules litany in the very module you want to get a handle to.
 
 

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

 

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

# test.py
import sys
def fn():
    print('hello world')
func_name = fn.__name__   ####这个可能是从url中获取的字符串
fn_obj = getattr(sys.modules[__name__], func_name)
            # 根据函数名(func_name),获得函数对象
fn_obj()
            # hello world

 

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

 

posted @ 2018-03-07 17:08  番茄土豆西红柿  阅读(7248)  评论(0编辑  收藏  举报
TOP