python反射

url = input("请输入url:")
target_module,target_func = url.split("/")
m = __import__("lib." + target_module,fromlist=True)
print(m)
if hasattr(m,target_func):
    target_func = getattr(m,target_func)
    print(target_func)
    r = target_func()
    print(r)
else:
    print("404")

account.py(在lib文件夹内)

def login():
    return "login"
def logout():
    return "logout"

commons.py(在lib文件夹内)

def f1():
    return "F1"

def f2():
    return "F2"

运行结果:

C:python3.5python.exe D:/python开发代码/Python之路/day9/find_index.py
请输入url:account/f1   
<module 'lib.account' from 'D:\python开发代码\Python之路\day9\lib\account.py'> #变量m的打印显示
404  #account里没有f1方法,所以显示404

----------------------------------------------------------
C:python3.5python.exe D:/python开发代码/Python之路/day9/find_index.py
请输入url:account/login
<module 'lib.account' from 'D:\python开发代码\Python之路\day9\lib\account.py'> #变量m的打印显示
<function login at 0x00000000009FB510>
login #account里有login方法,所以显示login

Process finished with exit code 0

  

原文地址:https://www.cnblogs.com/uglyliu/p/6134185.html