反射

python 反射

通过字符串的形式,导入模块

通过字符串的形式,去模块中寻找指定函数或者是全局变量,并执行。

1 #通过用户输入,来导入模块。
2 inp = input("请输入模块:")
3 print(inp,type(inp))
4 
5 dd = __import__(inp)  #等价于 import commons as dd 
6 ret = dd.f1()
7 print(ret)

 模块和功能都由用户输入

1 inp =  input("please input model:") #用户输入模块
2 inp1 = input("please input gongneng:")#用户输入功能
3 comm = __import__(inp)#等价于import commons 
4 dd = getattr(comm,inp1) #getattr 函数用于接收字符串,调用调用功能。getattr(xxx,xxx,NONE)none是默认值,没有找到函数则返回none
5 dd()

 

  

1 import commons
2 NAME = 'f1111'
3 target_func = getattr(commons, NAME, None)#函数NAME不存在的时,返回None
4 print(target_func)
1 import commons
2 
3 r = hasattr(commons,'naame') #commons模块中不存在naame函数时,返回False,存在返回True
4 print(r)
import  lib.test.com
from lib.test import com
r = __import__('lib.test.com', fromlist=True) #等价于import lib.test.com或from lib.test import com
print(r)

基于反射模拟web框架流程路由系统一
 1 from lib import  acccount
 2 
 3 url = input("请输入URL:")
 4 
 5 if url.endswith("login"):
 6     r = acccount.login()
 7     print(r)
 8 elif url.endswith("logout"):
 9     r = acccount.logout()
10     print(r)
11 elif  url.endswith("nb"):
12     r= acccount.nb()
13     print(r)
14 else:
15     print("404")

 

基于反射模拟web框架流程路由系统二

from lib import  acccount

url = input("请输入URL:")
r =  url.split("/")[-1]
if hasattr(acccount,r):#检查acccout模块中是否存在“r” 也就是用户输入的的模块
    ret = getattr(acccount,r)
    ret1= ret()
    print(ret1)
else:
    print("404")

 

基于反射模拟web框架流程路由系统三

 

from lib import  acccount
#模块名/函数
url = input("请输入URL:")
target_model , target_func = url.split("/")
m =  __import__("lib."+target_model, fromlist=True)#fromlist=True包含路径
if hasattr(m,target_func):#检查acccout模块中是否存在“r” 也就是用户输入的的模块
    ret = getattr(m,target_func)
    ret1= ret()
    print(ret1)
else:
    print("404")

 

 

 

posted @ 2019-06-20 21:44  Freechen0  阅读(77)  评论(0)    收藏  举报