标签:
了解反射前,我先看看内置方法__import__,还记得这个内置方法吗?
inp = input(‘请输入你要导入的模块:‘) mokuai = __import__(inp) #import xml as mokuai print(mokuai.__doc__)
import re str_func = input(‘请输入你要执行re下的方法:‘) tar_func = getattr(re,str_func) print(tar_func) #打印找到函数的内存地址
import re str_func = input(‘请输入你要执行re下的方法:‘) tar_func = getattr(re,str_func,None) #找到了就返回函数,没有找到就返回None,不设置None,没找到就报错 print(tar_func) #打印找到函数的内存地址
import re ret1 = hasattr(re,‘match‘) print(ret1) ret2 = hasattr(re,‘fjfijajfojg‘) print(ret2)
r = hasattr(commons,‘age‘) print(r) #False setattr(commons,‘age‘,lambda a:a + 1) r = getattr(commons,‘age‘) #没报错 ret = r(1) print(ret)
from lib import account url = input(‘请输入url:‘) inp = url.split(‘/‘)[-1] if hasattr(account,inp): func = getattr(account,inp) func() else: print(‘404‘)
url = input(‘请输入url:‘) target_module,target_func = url.split(‘/‘) m = __import__(‘lib.‘+target_module,fromlist=True) if hasattr(m,target_func): tar_func = getattr(m,target_func) r = tar_func() print(r) else: print(‘404‘)
欢迎大家对我的博客内容提出质疑和提问!谢谢
笔者:拍省先生
标签:
原文地址:http://www.cnblogs.com/xinsiwei18/p/5645244.html