python进阶之类的反射
有应用场景的技术才是有灵魂的技术------>最近同时问我,在python中,给你一个函数或者类的字符串名称,你怎么得到该函数和类,以下结合源码记录我得到的方式:
1.给一个函数的字符串"function"得到函数并运行
class TestA(object):
def get_test(self):
print("我是函数1") def instance(self):
print("我是函数2") ins = TestA()
get_test = getattr(ins, "get_test")
get_test()
我们运行得到结果
C:\Users\37521\Anaconda2\python.exe C:/mine/company1/new_media_backend/newmediaBE/wechat-public/public/app/api_1_0/test.py
我是函数1 Process finished with exit code 0
通过python的反射方法getattr达到我们想要的结果,然后我们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函数需要我们传一个对象,和一个字符串,然后从对象中找到和字符串同名的方法属性。
当然跟getattr对应的反射方法为,setattr和delattr,顾名思义这里不多解释。
2.第二个方法为eval函数
class TestA(object):
def get_test(self):
print("我是函数1") def instance(self):
print("我是函数2") @staticmethod
def test3():
print("我是静态方法") ins = TestA()
get_test = getattr(ins, "get_test")
get_test()
print("-----------------1-------------------")
instance = getattr(TestA, "instance")
instance(ins)
print("---------------2---------------------")
eval("instance")(ins)
print("-----------------3-------------------")
eval("TestA").test3()
我们在2处我们给eval函数传入一个instance函数字符串然后运行传出ins实例,在3出我们给eval函数传入TestA类字符串,然后运行类下的静态方法,我们看运行的结果如下
C:\Users\37521\Anaconda2\python.exe C:/mine/company1/new_media_backend/newmediaBE/wechat-public/public/app/api_1_0/test.py
我是函数1
-----------------1-------------------
我是函数2
---------------2---------------------
我是函数2
-----------------3-------------------
我是静态方法 Process finished with exit code 0
得到我们想要的结果,那我们就好奇eval函数是怎么实现可以传入一个字符串就去寻找对应的函数或者类对象,我们看一下eval函数的源码
def eval(source, globals=None, locals=None): # real signature unknown; restored from __doc__
"""
eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
pass
我们根据源码解释,首先解释器会我们传入的去locals和globals中去找我们传入的source为键找对应的值,如果未传入globals和locals就会去默认的glocals和locals中寻找,然后我们就好奇这个globals和locals是什么,然后我们运行一下
def globals(): # real signature unknown; restored from __doc__
"""
globals() -> dictionary Return the dictionary containing the current scope's global variables.
"""
return {} def locals(): # real signature unknown; restored from __doc__
"""
locals() -> dictionary Update and return a dictionary containing the current scope's local variables.
"""
return {}
看源码解释,globals为返回一个包含全局变量的字典,locals为返回一个包含本地变量的字典,然后运行这两个函数,看一下结果:
class TestA(object):
a=1
def get_test(self):
print("我是函数1") def instance(self):
print("我是函数2") @staticmethod
def test3():
print("我是静态方法") def b():
print(222) print(globals())
print(locals()) 结果:
{'b': <function b at 0x0000000002F46978>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/mine/company1/new_media_backend/newmediaBE/wechat-public/public/app/api_1_0/test.py', '__package__': None, 'TestA': <class '__main__.TestA'>, '__name__': '__main__', '__doc__': None}
{'b': <function b at 0x0000000002F46978>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/mine/company1/new_media_backend/newmediaBE/wechat-public/public/app/api_1_0/test.py', '__package__': None, 'TestA': <class '__main__.TestA'>, '__name__': '__main__', '__doc__': None}
3.根据上打印的globals函数的结果,那我们也想到根源的获取类对象的方法
globals()函数运行的结果为一个字典,类对象的字符串为建,类对象为值,所以我们可以这样得到:
class TestA(object):
a=1
def get_test(self):
print("我是函数1") def instance(self):
print("我是函数2") @staticmethod
def test3():
print("我是静态方法") # print(globals())
# print(locals())
globals()["TestA"].test3() 结果如下:
C:\Users\37521\Anaconda2\python.exe C:/mine/company1/new_media_backend/newmediaBE/wechat-public/public/app/api_1_0/test.py
我是静态方法 Process finished with exit code 0
globals()["TestA"].test3()通过字典操作得到类对象,在运行类下的静态方法。 以上是我总结的3种,给出函数或类的字符串得到对应函数和类对象的方法,
从前我一直抄袭别人的博客,现在我希望能反馈输出一些有用的原创,一直在路上
python进阶之类的反射的更多相关文章
- Python进阶----反射(四个方法),函数vs方法(模块types 与 instance()方法校验 ),双下方法的研究
Python进阶----反射(四个方法),函数vs方法(模块types 与 instance()方法校验 ),双下方法的研究 一丶反射 什么是反射: 反射的概念是由Smith在1982年首次提出的 ...
- Python开发基础-Day22反射、面向对象进阶
isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象,如果是返回True class Foo ...
- Python进阶编程 反射
1.7反射 python面向对象中的反射:通过字符串的形式操作对象相关的属性.python中的一切事物都是对象(都可以使用反射) class Foo: f = '类的静态变量' def __init_ ...
- python进阶(7):面向对象进阶
学了面向对象三大特性继承,多态,封装.今天我们看看面向对象的一些进阶内容,反射和一些类的内置函数. 一.isinstance和issubclass class Foo: pass class Son( ...
- python进阶_浅谈面向对象进阶
python进阶_浅谈面向对象进阶 学了面向对象三大特性继承,多态,封装.今天我们看看面向对象的一些进阶内容,反射和一些类的内置函数. 一.isinstance和issubclass class F ...
- Python进阶:函数式编程实例(附代码)
Python进阶:函数式编程实例(附代码) 上篇文章"几个小例子告诉你, 一行Python代码能干哪些事 -- 知乎专栏"中用到了一些列表解析.生成器.map.filter.lam ...
- Python进阶 - 对象,名字以及绑定
Python进阶 - 对象,名字以及绑定 1.一切皆对象 Python哲学: Python中一切皆对象 1.1 数据模型-对象,值以及类型 对象是Python对数据的抽象.Python程序中所有的数据 ...
- Python进阶-继承中的MRO与super
Python进阶-继承中的MRO与super 写在前面 如非特别说明,下文均基于Python3 摘要 本文讲述Python继承关系中如何通过super()调用"父类"方法,supe ...
- Python进阶 - 命名空间与作用域
Python进阶 - 命名空间与作用域 写在前面 如非特别说明,下文均基于Python3 命名空间与作用于跟名字的绑定相关性很大,可以结合另一篇介绍Python名字.对象及其绑定的文章. 1. 命名空 ...
随机推荐
- 去掉input密码框自动补全功能
<input name="password" autocomplete="off" hidden> <input type="pas ...
- Excel: assign label to scatter chart using specific cell values
ref: https://www.get-digital-help.com/custom-data-labels-in-x-y-scatter-chart/ Improve your X Y Scat ...
- Bugku 杂项 眼见非实(ISCCCTF)
眼见非实(ISCCCTF) 下载文件后,用winhex打开 发现文件头为50 4B 03 04说明是一个压缩文件,还可以看到其中有.docx文件 更改文件后缀为 .zip 解压后发现 这个文件用wor ...
- java 如何实现大文件上传下载(传输)各种格式
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- Python用MyQR生成自定义个性二维码
MyQR是一个能够生成自定义二维码的python第三方库,根据需要能够生成普通二维码.带背景图片的艺术二维码.动态二维码. 1.MyQR安装 安装非常简单,直接用pip install MyQR,需要 ...
- C++ STL bitset总结
基础用法 C++ Reference 神犇博客 余下的就是例题了 [BZOJ3687]简单题 考虑\(DP\),设\(f[i][j]\)表示前\(i\)个元素的算数和为\(j\)的子集个数,有: \[ ...
- BootStrap 用法
1 下载bootstrap组件 2 在jsp页面中加入bootstrap <link rel="stylesheet" type="text/css" ...
- 2019前端面试题汇总(vue)
毕业之后就在一直合肥小公司工作,没有老司机.没有技术氛围,在技术的道路上我只能独自摸索.老板也只会画饼充饥,前途一片迷茫看不到任何希望.于是乎,我果断辞职,在新年开工之际来到杭州,这里的互联网公司应该 ...
- 大数据笔记(十)——Shuffle与MapReduce编程案例(A)
一.什么是Shuffle yarn-site.xml文件配置的时候有这个参数:yarn.nodemanage.aux-services:mapreduce_shuffle 因为mapreduce程序运 ...
- [转]python常用的十进制、16进制、字符串、字节串之间的转换
阅读目录(Content) 整数之间的进制转换: 字符串转整数: 字节串转整数: 整数转字节串: 字符串转字节串: 字节串转字符串: 测试用的python源码 进行协议解析时,总是会遇到各种各样的数据 ...