我们在来复习一下反射
<代码> # demo.py中的程序
#?usr/bin/env python
utf - 8编码:
def Foo ():
打印“demo.foo”
#主程序
#?usr/bin/env python
utf - 8编码:
str1=把菔尽?
str2=癋oo”
模块=__import__ (str1) #==进口演示
str2 funk=getattr(模块)
# getattr相当于房户户演示模块中的Foo函数
恐惧()
#可以看到getater就是找到foo函数,并且赋给funk函数。
结果:demo.foo 代码>
我们引入反射的应用实例
<代码> # account.py文件
#?usr/bin/env python
utf - 8编码:
#登录网站相关文件
def登录():
打印“登录”
def注销():
打印“注销”
# index.py文件
#?usr/bin/env python
utf - 8编码:
从后端导入账户
data=https://www.yisu.com/zixun/raw_input(“请输入URL:”)
数组=data.split (“/?
如果data=https://www.yisu.com/zixun/=账户/登录:
account.login ()
elif data=https://www.yisu.com/zixun/=的帐户/注销:
account.logout ()
#这里我们的大型网站如果有100个URL是不是我们要写100个如果呢,这里我们就可以用反射动态获取。在下面介绍代码>
一般web获取URL的原理
<代码> #这里admin.py和account.py都时我们URL的一个分页面
# admin.py文件
#?usr/bin/env python
utf - 8编码:
def指数():
打印的欢迎登陆后台管理的
# account.py文件
#?usr/bin/env python
utf - 8编码:
#登录网站相关文件
def登录():
打印“登录”
def注销():
打印“注销”
# index.py文件
#?usr/bin/env python
utf - 8编码:
data=https://www.yisu.com/zixun/raw_input(“请输入URL:”)
数组=data.split (“/?
userspance=__import__(“后端”。+阵列[0])
模型=getattr (userspance阵列[0])
func=getattr(模型中,阵列[1])
#相当于先导入一个文件夹,在文件夹中在导入那个模块,在执行函数。
#这里__import__相当于先导入进口backend.account,然后在导入模块,在执行登录()函数,也就是跟正常的没有区别,先进口端,然后backend.account,然后在backend.account.login
#这里我们正常导入模块时导入bachend。账户,执行的时候是使用backend.account.login(),所以我们这里在使用两次次getattr,这下应该差不多明白了
函数()
#一次执行结果:
请输入URL: admin/索引
欢迎登陆后台管理代码>