python 反射(__import__、getattr)
#反射的作用在于模块导入,函数调用时简化代码
以URL为例:
假设URL的形式是A/B
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 常规
'''
from backend import login,logout,admin
data = raw_input('请输入URL')
if data == 'login/mylogin':
login.mylogin()
elif data == 'logout/mylogout':
logout.mylogout()
elif data == 'admin/index':
admin.index()
else:
print 'error'
'''
# 反射
data = raw_input('请输入URL')
arr = data.split('/')
namespace = __import__('backend.' + arr[0]) # import backend.admin
model = getattr(namespace, arr[0]) # model = backend.admin
func = getattr(model, arr[1]) # backend.admin.index()
func()
# import backend.admin
# backend.admin.index()