有应用场景的技术才是有灵魂的技术------>最近同时问我,在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进阶之类的反射的更多相关文章

  1. Python进阶----反射(四个方法),函数vs方法(模块types 与 instance()方法校验 ),双下方法的研究

    Python进阶----反射(四个方法),函数vs方法(模块types 与 instance()方法校验 ),双下方法的研究 一丶反射 什么是反射: ​ 反射的概念是由Smith在1982年首次提出的 ...

  2. Python开发基础-Day22反射、面向对象进阶

    isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象,如果是返回True class Foo ...

  3. Python进阶编程 反射

    1.7反射 python面向对象中的反射:通过字符串的形式操作对象相关的属性.python中的一切事物都是对象(都可以使用反射) class Foo: f = '类的静态变量' def __init_ ...

  4. python进阶(7):面向对象进阶

    学了面向对象三大特性继承,多态,封装.今天我们看看面向对象的一些进阶内容,反射和一些类的内置函数. 一.isinstance和issubclass class Foo: pass class Son( ...

  5. python进阶_浅谈面向对象进阶

    python进阶_浅谈面向对象进阶 学了面向对象三大特性继承,多态,封装.今天我们看看面向对象的一些进阶内容,反射和一些类的内置函数. 一.isinstance和issubclass  class F ...

  6. Python进阶:函数式编程实例(附代码)

    Python进阶:函数式编程实例(附代码) 上篇文章"几个小例子告诉你, 一行Python代码能干哪些事 -- 知乎专栏"中用到了一些列表解析.生成器.map.filter.lam ...

  7. Python进阶 - 对象,名字以及绑定

    Python进阶 - 对象,名字以及绑定 1.一切皆对象 Python哲学: Python中一切皆对象 1.1 数据模型-对象,值以及类型 对象是Python对数据的抽象.Python程序中所有的数据 ...

  8. Python进阶-继承中的MRO与super

    Python进阶-继承中的MRO与super 写在前面 如非特别说明,下文均基于Python3 摘要 本文讲述Python继承关系中如何通过super()调用"父类"方法,supe ...

  9. Python进阶 - 命名空间与作用域

    Python进阶 - 命名空间与作用域 写在前面 如非特别说明,下文均基于Python3 命名空间与作用于跟名字的绑定相关性很大,可以结合另一篇介绍Python名字.对象及其绑定的文章. 1. 命名空 ...

随机推荐

  1. 使用QT创建系统托盘

    使用QT来创建一个系统托盘,事实上是一件很简单的事.为什么这么说?一是因为QT文档给出了比较详细的例子,二是QT的结构比较优雅,设计风格统一.但是在动手之前,我们要从哪里下手?虽然QT文档给出了一个比 ...

  2. python碎片 - 函数参数

    一个*传参: 方式1:如果想传一个列表中的值,实参前加*.如: *[1,2,3] 方式2:直接传入一个列表,不加*.如[1,2,3],则传入的是一整个列表,包括[] 两个**传参: 方式1,:{nam ...

  3. ZROI 19.07.28 序列数据结构/jk

    写在前面 dls:"我不会数据结构,但是APIO的数据结构场我写了,还是蛮简单的." T1 CF643G Sol: 有一个\(O(n\log^2n)\)的做法:假设将区间排好序,取 ...

  4. git-bash.exe参数

    baidu搜了很多, 没有结果.估计大家都没有这个场景.google了一下, 几篇非常不错的结果: https://superuser.com/questions/1104567/how-can-i- ...

  5. 【leetcode】493. Reverse Pairs

    题目如下: 解题思路:本题要求的是数组每个元素和所有排在这个元素后面的元素的值的二倍做比较.我们可以先把数组所有元素的二倍都算出来,存入一个新的数组newlist,并按升序排好.而后遍历nums数组的 ...

  6. pytest-生成测试报告

    import pytest """ 使用pytest编写用例,必须遵守以下规则: (1)测试文件名必须以"test_"开头或者"_test& ...

  7. JavaScript正则表达式(四)

    正则表达式方法 一.test方法 用于测试字符串参数中是否存在匹配正则表达式模式的字符串 如果存在就返回true,否则返回false 实例: 1.使用test方法不设置g标志时  2.使用test方法 ...

  8. HDU 6616 Divide the Stones

    目录 题面 中文题意 比赛惨状 我的走不通的思路 \(m\)是偶数的情况 \(m\)是奇数的情况 题解的思路 另一些思路 源代码 题面 Time limit 3000 ms Memory limit ...

  9. Dmango cxrf 自定义分页 缓存 session 序列化 信号量 知识点

    参考https://www.cnblogs.com/wupeiqi/articles/5246483.html

  10. Python 元组遍历排序操作方法

    在Python不可变数据类型中,有一个比较重要的角色那就是元组( tuple ).如果某个对像被定义为元组类型,那么就意味着它的值不能被修改,除非重新定义一个新的对像.元组和List列表常被放在一起进 ...