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. 命名空 ...
随机推荐
- 强大的VS插件CodeRush发布v19.1.4|支持Visual Studio 2019
CodeRush是一个强大的Visual Studio .NET 插件,它利用整合技术,通过促进开发者和团队效率来提升开发者体验. [CodeRush for Visual Studio v19.1. ...
- HBase过滤器(转载)
HBase为筛选数据提供了一组过滤器,通过这个过滤器可以在HBase中的数据的多个维度(行,列,数据版本)上进行对数据的筛选操作,也就是说过滤器最终能够筛选的数据能够细化到具体的一个存储单元格上(由行 ...
- python-jsonpath、findall返回值提取
findall import re """ "d"表示取数字0-9, "D"表示不要数字, "w"在正则里面代 ...
- 运输计划noip
靠!这道题TM搞了我好几天,真是烦死人!!!早上打了一个倍增的TM只有95分QAQ... 然后一气之下开始不断卡常,各种玄学优化,可是就是T..TAT.. 可恶!晚上我就直接打了个tarjan,还好跑 ...
- Internet History, Technology, and Security(week7)——Technology: Application Protocols
Layer 4: Applications Application Layer TCP提供了“a reliable pipe”(一个坚固的水管)连接用户和服务器,确保了数据能准确不出意外地传输,所以A ...
- 51nod1584加权约数和
题目大意: 求: \[ \sum_{i-1}^n\sum_{j=1}^nmax(i,j)\sigma(i*j) \] 题解 对于这个\(\max\),套路的把它转化成: \[ 2*\sum_{i=1} ...
- D1. Kirk and a Binary String (easy version)
D1. Kirk and a Binary String (easy version) 01串找最长不降子序列 给定字符串s,要求生成一个等长字符串t,使得任意l到r位置的最长不降子序列长度一致 从后 ...
- [spring cloud feign] [bug] 使用对象传输get请求参数
前言 最近在研究 srping cloud feign ,遇到了一个问题,就是当 get 请求 的参数使用对象接收时,就会进入熔断返回.经过百度,发现网上大部分的解决方案都是将请求参数封装到Reque ...
- 170831-关于JdbcTemplate声明式事务-操作步骤-例子
创建一个动态web工程 加入jar包 3.创建一份jdbc.properties文件 4.在spring配置文件中配置数据源 5.测试数据源: 6.配置jdbcTemplate: 7.创建Dao类 & ...
- np.asarray(a, dtype=None, order=None)
np.asarray(a, dtype=None, order=None) 参数a:可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组 参数dtype=None, order=N ...