1. 什么是反射?

它的核心本质其实就是基于字符串的事件驱动,通过字符串的形式去操作对象的属性或者方法

2. 反射的优点

一个概念被提出来,就是要明白它的优点有哪些,这样我们才能知道为什么要使用反射。

2.1 场景构造

开发1个网站,由两个文件组成,一个是具体执行操作的文件commons.py,一个是入口文件visit.py

需求:需要在入口文件中设置让用户输入url, 根据用户输入的url去执行相应的操作

# commons.py
def login():
print("这是一个登陆页面!") def logout():
print("这是一个退出页面!") def home():
print("这是网站主页面!")
# visit.py
import commons def run():
inp = input("请输入您想访问页面的url: ").strip()
if inp == 'login':
commons.login()
elif inp == 'logout':
commons.logout()
elif inp == 'index':
commons.home()
else:
print('404') if __name__ == '__main__':
run()

运行run方法后,结果如下:

请输入您想访问页面的url:  login
这是一个登陆页面!

提问:上面使用if判断,根据每一个url请求去执行指定的函数,若commons.py中有100个操作,再使用if判断就不合适了

回答:使用python反射机制,commons.py文件内容不变,修改visit.py文件,内容如下

import commons

def run():
inp = input("请输入您想访问页面的url: ").strip()
if hasattr(commons, inp):
getattr(commons, inp)()
else:
print("404") if __name__ == '__main__':
run()

使用这几行代码,可以应对​​commons.py​​文件中任意多个页面函数的调用!

反射中的内置函数

getattr

def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass

​​getattr()​​​函数的第一个参数需要是个对象,上面的例子中,我导入了自定义的commons模块,commons就是个对象;第二个参数是指定前面对象中的一个方法名称。

​​getattr(x, 'y')​​​ 等价于执行了 ​x.y​​​。假如第二个参数输入了前面对象中不存在的方法,该函数会抛出异常并退出。所以这个时候,为了程序的健壮性,我们需要先判断一下该对象中有没有这个方法,于是用到了​​hasattr()​​函数

hasattr

def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass

​​hasattr()​​​函数返回对象是否拥有指定名称的属性,简单的说就是检查在第一个参数的对象中,能否找到与第二参数名相同的方法。源码的解释还说,该函数的实现其实就是调用了​​getattr()​​​函数,只不过它捕获了异常而已。所以通过这个函数,我们可以先去判断对象中有没有这个方法,有则使用​​getattr()​​来获取该方法。

setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass

​​setattr()​​​函数用来给指定对象中的方法重新赋值(将新的函数体/方法体赋值给指定的对象名)仅在本次程序运行的内存中生效。​​setattr(x, 'y', v)​​​ 等价于 ​​x.y = v​

delattr

def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y''
"""
pass

删除指定对象中的指定方法,特别提示:只是在本次运行程序的内存中将该方法删除,并没有影响到文件的内容

__import__模块反射

接着上面网站的例子,现在一个后台文件已经不能满足我的需求,这个时候需要根据职能划分后台文件,现在我又新增了一个​​user.py这个用户类的文件,也需要导入到首页以备调用。

但是,上面网站的例子,我已经写死了只能指定commons模块的方法任意调用,现在新增了user模块,那此时我又要使用if判断?

答:不用,使用Python自带的函数__import__

由于模块的导入也需要使用Python反射的特性,所以模块名也要加入到url中,所以现在url请求变成了类似于​​commons/visit​​的形式

# user.py
def add_user():
print('添加用户') def del_user():
print('删除用户')
# commons.py
def login():
print("这是一个登陆页面!") def logout():
print("这是一个退出页面!") def home():
print("这是网站主页面!")
# visit.py
def run():
inp = input("请输入您想访问页面的url: ").strip()
# modules代表导入的模块,func代表导入模块里面的方法
modules, func = inp.split('/')
obj_module = __import__(modules)
if hasattr(obj_module, func):
getattr(obj_module, func)()
else:
print("404") if __name__ == '__main__':
run()

最后执行run函数,结果如下:

请输入您想访问页面的url:  user/add_user
添加用户 请输入您想访问页面的url: user/del_user
删除用户

现在我们就能体会到__import__的作用了,就是把字符串当做模块去导入。

但是如果我的网站结构变成下面的

|- visit.py
|- commons.py
|- user.py
|- lib
|- __init__.py
|- connectdb.py

现在我想在​​visit​​​页面中调用​​lib​​​包下​​connectdb​​模块中的方法,还是用之前的方式调用可以吗?

# connectdb.py
def conn():
print("已连接mysql")
# visit.py
def run():
inp = input("请输入您想访问页面的url: ").strip()
# modules代表导入的模块,func代表导入模块里面的方法
modules, func = inp.split('/')
obj_module = __import__('lib.' + modules)
if hasattr(obj_module, func):
getattr(obj_module, func)()
else:
print("404") if __name__ == '__main__':
run()

运行run命令,结果如下:

请输入您想访问页面的url:  connectdb/conn
404

结果显示找不到,为了测试调用lib下的模块,我抛弃了对所有同级目录模块的支持,所以我们需要查看__import__源码

def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
"""
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module Import a module. Because this function is meant for use by the Python
interpreter and not for general use, it is better to use
importlib.import_module() to programmatically import a module. The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. The level argument is used to determine whether to
perform absolute or relative imports: 0 is absolute, while a positive number
is the number of parent directories to search relative to the current module.
"""
pass

​​__import__​​​函数中有一个​​fromlist​​参数,源码解释说,如果在一个包中导入一个模块,这个参数如果为空,则return这个包对象,如果这个参数不为空,则返回包下面指定的模块对象,所以我们上面是返回了包对象,所以会返回404的结果,现在修改如下:

# visit.py
def run():
inp = input("请输入您想访问页面的url: ").strip()
# modules代表导入的模块,func代表导入模块里面的方法
modules, func = inp.split('/')
# 只新增了fromlist=True
obj_module = __import__('lib.' + modules, fromlist=True)
if hasattr(obj_module, func):
getattr(obj_module, func)()
else:
print("404") if __name__ == '__main__':
run()

运行run方法,结果如下:

请输入您想访问页面的url:  connectdb/conn
已连接mysql

成功了,但是我写死了lib前缀,相当于抛弃了commonsuser两个导入的功能,所以以上代码并不完善,需求复杂后,还是需要对请求的url做一下判断

def getf(module, func):
"""
抽出公共部分
"""
if hasattr(module, func):
func = getattr(module, func)
func()
else:
print('404') def run():
inp = input("请输入您想访问页面的url: ").strip()
if len(inp.split('/')) == 2:
# modules代表导入的模块,func代表导入模块里面的方法
modules, func = inp.split('/')
obj_module = __import__(modules)
getf(obj_module, func)
elif len(inp.split("/")) == 3:
p, module, func = inp.split('/')
obj_module = __import__(p + '.' + module, fromlist=True)
getf(obj_module, func) if __name__ == '__main__':
run()

运行run函数,结果如下:

请输入您想访问页面的url:  lib/connectdb/conn
已连接mysql 请输入您想访问页面的url: user/add_user
添加用户

当然你也可以继续优化代码,现在只判断了有1个斜杠和2个斜杠的,如果目录层级更多呢,这个暂时不考虑,本次是为了了解python的反射机制

最新文章

  1. [转]Modernizr的介绍和使用
  2. 【转】C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1)
  3. 有没有好用的开源sql语法分析器? - 匿名用户的回答 - 知乎
  4. Android核心分析 之二方法论探讨之概念空间篇
  5. 点击UITableviewCell展开收缩
  6. (转)Yale CAS + .net Client 实现 SSO(3)
  7. ubuntu禁用笔记本自带键盘
  8. CQRS学习——一个例子(其六)
  9. 序列化layer创建的弹出表单并ajax提交
  10. Sql Server 2008开发版(Developer Edition)过期升级企业版(Enterprise Edition)失败后安装学习版(Express Edition)
  11. PBXCp Error
  12. Ubuntu 14.04 16.04 17.10 + Win10 双系统安装记录 + 分区大小选择办法
  13. myeclipse2017下载安装与破解详细教程
  14. php 计算坐标点方圆周围多少米的坐标算法
  15. 微信小程序之发送模板消息(通过openid推送消息给用户)
  16. [Python设计模式] 第2章 商场收银软件——策略模式
  17. Flex 数组问题!
  18. [摘]HttpContext, HttpRequest, HttpResponse, HttpRuntime, HttpServerUtility
  19. Android常见问题——Genymotion无法启动问题
  20. Wishbone总线从接口转Xilinx MIG (Spartan 6)

热门文章

  1. CF-1453B
  2. 【PMP学习笔记】第5章 项目范围管理
  3. 声明式HTTP客户端-Feign 使用入门详解
  4. docker-compose入门--翻译
  5. C#,启动exe程序并传参(参数间带&符号)方法
  6. 9. 第八篇 kube-controller-manager安装及验证
  7. 知识广度 vs 知识深度
  8. mongodb集群搭建(分片+副本)开启安全认证
  9. 13. Fluentd输出插件:in_forward用法详解
  10. Elasticsearch:foreach 摄入处理器介绍---处理未知长度数组中的元素