有应用场景的技术才是有灵魂的技术------>最近同时问我,在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. 【GDOI 2016 Day1】疯狂动物城

    题目 分析 注意注意:码农题一道,打之前做好心理准备. 对于操作1.2,修改或查询x到y的路径,显然树链剖分. 对于操作2,我们将x到y的路径分为x到lca(x,y)和lca(x,y)到y两部分. 对 ...

  2. [洛谷P1864] NOI2009 二叉查找树

    问题描述 已知一棵特殊的二叉查找树.根据定义,该二叉查找树中每个结点的数据值都比它左儿子结点的数据值大,而比它右儿子结点的数据值小. 另一方面,这棵查找树中每个结点都有一个权值,每个结点的权值都比它的 ...

  3. HTML Tag, 把 WCAG 的标准和语义网的目标进行代码上的体现

    1. 文档声明:<!Doctype> 其实这跟 WCAG 根本上连不上什么直接关系,但为了一个兼容性更好,特别是向后兼容的页面,我推荐你这样写: <!Doctype html> ...

  4. React Native 之导航栏

    一定要参考官网: https://reactnavigation.org/docs/en/getting-started.html 代码来自慕课网:https://www.imooc.com/cour ...

  5. Vue框架基础概要

    Vue.js是什么? Vue.js(读音 /vjuː/,类似于 view 的读音)是一套构建用户界面(user interface)的渐进式框架.与其他重量级框架不同的是,Vue 从根本上采用最小成本 ...

  6. asp.net (web)选择文件夹 上传文件

    1 背景 用户本地有一份txt或者csv文件,无论是从业务数据库导出.还是其他途径获取,当需要使用蚂蚁的大数据分析工具进行数据加工.挖掘和共创应用的时候,首先要将本地文件上传至ODPS,普通的小文件通 ...

  7. A - Race to 1 Again

    题目 Rimi learned a new thing about integers, which is - any positive integer greater than 1 can be di ...

  8. 【PowerOJ1738&网络流24题】最小路径覆盖问题 (最大流)

    题意: 思路: [问题分析] 有向无环图最小路径覆盖,可以转化成二分图最大匹配问题,从而用最大流解决. [建模方法] 构造二分图,把原图每个顶点i拆分成二分图X,Y集合中的两个顶点Xi和Yi.对于原图 ...

  9. 如何理解重载与重写——Overload vs Override/Overwrite

    重载: 在同一个类中,拥有类似功能的同名方法之间的关系叫做重载. 重载的条件:1.具有相同方法名和类似功能: 2.参数的类型或者个数不同: 3.与返回值无关: 重写: 在子父类的继承关系中,子类继承父 ...

  10. POJ 1380 Equipment Box (暴力枚举)

    Equipment Box 题目链接: http://acm.hust.edu.cn/vjudge/contest/130510#problem/B Description There is a la ...