zoukankan      html  css  js  c++  java
  • Python的自省机制与Python 的反射机制

    Python的自省机制

    简单直白一点:自省就是面向对象的语言所写的程序在运行时,能够知道对象的类型。简单一句就是,运行时能够获知对象的类型。

    Python中比较常见的自省(introspection)机制(函数用法)有: dir(),type(), hasattr(), isinstance(),通过这些函数,我们能够在程序运行时得知对象的类型,判断对象是否存在某个属性,访问对象的属性

    dir()

     dir() 函数可能是 Python 自省机制中最著名的部分了。它返回传递给它的任何对象的属性名称经过排序的列表。如果不指定对象,则 dir() 返回当前作用域中的名称。让我们将 dir() 函数应用于 keyword 模块,并观察它揭示了什么:

    >>> import keyword
    >>> dir(keyword)
    ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']


     type()
     type() 函数有助于我们确定对象是字符串还是整数,或是其它类型的对象。它通过返回类型对象来做到这一点,可以将这个类型对象与 types 模块中定义的类型相比较:

    >>> type(42)
    <class 'int'>
    >>> type([])
    <class 'list'>


      hasattr()

     对象拥有属性,并且 dir() 函数会返回这些属性的列表。但是,有时我们只想测试一个或多个属性是否存在。如果对象具有我们正在考虑的属性,那么通常希望只检索该属性。这个任务可以由 hasattr() 和 getattr() 函数来完成.

    >>> hasattr(id, '__doc__')
    True

     
     isinstance() 
     可以使用 isinstance() 函数测试对象,以确定它是否是某个特定类型或定制类的实例:

    >>> isinstance("python", str)
    True

    getattr(object,name,default):

    作用:返回object的名称为name的属性的属性值,如果属性name存在,则直接返回其属性值;如果属性name不存在,则触发AttribetError异常或当可选参数default定义时返回default值。

    这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。

    下面我们使用小例子来说明它们的用法:

    复制代码
    import func_file       #自定义python模块
    cs=input('请输入要访问的URL:')
    if cs=='loggin':
     func_file.loggin()
    if cs =='home':
     func_file.home()
    if cs =='':
     pass#以下省略
    复制代码

    当我定义一个自定义模块,去调用其中的方法的时候,使用if去判断时,如果模块内用很多方法,会大大影响开发的效率,代码冗余差,显然这是不可取的。下面我们使用hasattr()函数来实现我们的需求:

    示例如下:

    复制代码
    import func_file       #自定义python模块,需事先存在
    def run():
     while True:
        cs=input('请输入要访问的URL:')
        #hasattr利用字符串的形式去对象(模块)中操作(寻找)成员
        if hasattr(func_file,cs):            #判断用户输入的URL是否在func_file模块中
            func=getattr(func_file,cs)       #有则将func_file模块下的cs函数赋值     
            func()                           #等同于执行func_file模块下的cs函数
        else:
            print('404')#定义错误页面
    run()
    复制代码

    我们导入一个自定义模块后,gatattr可以根据输入的内容动态加载,利用hasattr()函数来判断用户输入的是否存在,不存在则调用自定义方法。

    是不是感觉和我们打开网址URL很类似啊!

    上一个示例有一个问题,在实际情况中,我们的功能函数可能存放在很多模块中,每一个都需要单独导入,那我们可不可以利用getattr()函数去动态加载模块呢?当然可以啦

    请看示例:

    复制代码
    def run():
     while True:
        cs=input('请输入:')
        v,k=cs.split('/')  #获得输入的模块和模块的方法
        obj=__import__('lib.'+v,fromlist=True)  #调用lib目录下的模块fromlist=True按路径连接的方式导入
        if hasattr(obj,k):
           f= getattr(obj,k)
           f()
        else:
            print('404')
    if __name__ == '__main__':
         run()
    复制代码

    是不是感到getattr很强大啊。其实,getattr()就是实现python反射的一块积木,结合其它方法如setattr(),dir() 等,我们可以还可以做出很多有趣的事情。

    Python 的反射机制

    python的反射,它的核心本质其实就是利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!

    熟悉JAVA的程序员,一定经常和Class.forName打交道。在很多框架中(Spring,eclipse plugin机制)都依赖于JAVA的反射能力,而在python中,也同样有着强大的反射能力。Python作为一门动态语言,当然不会缺少这一重要功能。然而,在网络上却很少见到有详细或者深刻的剖析论文。下面结合一个web路由的实例来阐述python的反射机制的使用场景和核心本质。

    1、前言

    1
    2
    3
    4
    5
    def f1():
        print("f1是这个函数的名字!")
      
    s = "f1"
    print("%s是个字符串" % s)

    在上面的代码中,我们必须区分两个概念,f1和“f1"。前者是函数f1的函数名,后者只是一个叫”f1“的字符串,两者是不同的事物。我们可以用f1()的方式调用函数f1,但我们不能用"f1"()的方式调用函数。说白了就是,不能通过字符串来调用名字看起来相同的函数!

     

    2、web实例

    考虑有这么一个场景,根据用户输入的url的不同,调用不同的函数,实现不同的操作,也就是一个url路由器的功能,这在web框架里是核心部件之一。下面有一个精简版的示例:

    首先,有一个commons模块,它里面有几个函数,分别用于展示不同的页面,代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''
       commons.py
    '''
     
    def login():
        print('this is login page...')
     
    def logout():
        print('this is logout page...')
     
    def home():
        print('this is home page of the website...')

    其次,有一个visit模块,作为程序入口,接受用户输入,展示相应的页面,代码如下:(这段代码是比较初级的写法)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''
    visit.py
    '''
     
    import commons
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        if inp == 'login':
            commons.login()
        elif inp == 'logout':
            commons.logout()
        elif inp == 'home':
            commons.home()
        else:
            print('page not found 404...')
     
    if __name__ == '__main__':
        run()

    运行结果如下:

    1
    2
    please put the website's url you want to access: home
    this is home page of the website...

    这就实现了一个简单的WEB路由功能,根据不同的url,执行不同的函数,获得不同的页面。

    但是,如果commons模块里有成百上千个函数呢(这非常正常)?。难道你在visit模块里写上成百上千个elif?显然这是不可能的!那么怎么破?

     

    3、 反射

    仔细观察visit中的代码,我们会发现用户输入的url字符串和相应调用的函数名好像!如果能用这个字符串直接调用函数就好了!但是,前面我们已经说了字符串是不能用来调用函数的。为了解决这个问题,python为我们提供一个强大的内置函数:getattr!我们将前面的visit修改一下,代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    import commons
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        func = getattr(commons, inp)
        func()
     
    if __name__ == '__main__':
        run()

    首先说明一下getattr函数的使用方法:它接收2个参数,前面的是一个对象或者模块,后面的是一个字符串,注意了!是个字符串!

      例子中,用户输入储存在inp中,这个inp就是个字符串,getattr函数让程序去commons这个模块里,寻找一个叫inp的成员(是叫,不是等于),这个过程就相当于我们把一个字符串变成一个函数名的过程。然后,把获得的结果赋值给func这个变量,实际上func就指向了commons里的某个函数。最后通过调用func函数,实现对commons里函数的调用。这完全就是一个动态访问的过程,一切都不写死,全部根据用户输入来变化。

      执行上面的代码,结果和最开始的是一样的。

      这就是python的反射,它的核心本质其实就是利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!

      这段话,不一定准确,但大概就是这么个意思。

    复制代码
    1 >>> help(getattr)
    2 Help on built-in function getattr in module builtins:
    3 
    4 getattr(...)
    5     getattr(object, name[, default]) -> value
    6     
    7     Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    8     When a default argument is given, it is returned when the attribute doesn't
    9     exist; without it, an exception is raised in that case.
    复制代码

     

    4、 进一步完善

    上面的代码还有个小瑕疵,那就是如果用户输入一个非法的url,比如jpg,由于在commons里没有同名的函数,肯定会产生运行错误,具体如下:

    1
    2
    3
    4
    5
    6
    7
    please put the website's url you want to access: jpg
    Traceback (most recent call last):
      File "E:/python14_workspace/s14/day07/reverberate/visit.py", line 15, in <module>
        run()
      File "E:/python14_workspace/s14/day07/reverberate/visit.py", line 11, in run
        func = getattr(commons, inp)
    AttributeError: 'module' object has no attribute 'jpg'

    那怎么办呢?其实,python考虑的很全面了,它同样提供了一个叫hasattr的内置函数,用于判断commons中是否具有某个成员。我们将代码修改一下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    import commons
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        if hasattr(commons, inp):
            func = getattr(commons, inp)
            func()
        else:
            print('page not found 404...')
     
    if __name__ == '__main__':
        run()

    通过hasattr的判断,可以防止非法输入错误,并将其统一定位到错误页面。

    其实,研究过python内置函数的朋友,应该注意到还有delattr和setattr两个内置函数。从字面上已经很好理解他们的作用了。

    python的四个重要内置函数:getattr、hasattr、delattr和setattr较为全面的实现了基于字符串的反射机制。他们都是对内存内的模块进行操作,并不会对源文件进行修改。

    复制代码
     1 >>> help(hasattr)
     2 Help on built-in function hasattr in module builtins:
     3 
     4 hasattr(...)
     5     hasattr(object, name) -> bool
     6     
     7     Return whether the object has an attribute with the given name.
     8     (This is done by calling getattr(object, name) and catching AttributeError.)
     9 
    10 >>> help(delattr)
    11 Help on built-in function delattr in module builtins:
    12 
    13 delattr(...)
    14     delattr(object, name)
    15     
    16     Delete a named attribute on an object; delattr(x, 'y') is equivalent to
    17     ``del x.y''.
    18 
    19 >>> help(setattr)
    20 Help on built-in function setattr in module builtins:
    21 
    22 setattr(...)
    23     setattr(object, name, value)
    24     
    25     Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    26     ``x.y = v''.
    27 
    28 >>> 
    复制代码
    复制代码
     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author: antcolonies
     4 
     5 def bulk(self):
     6     print('%s is yelling...' %self.name)
     7 
     8 class Dog(object):
     9     def __init__(self, name):
    10         self.name = name
    11 
    12     def eat(self, food):
    13         print('%s is eating ...%s' %(self.name, food))
    14 
    15 d = Dog('Tim')
    16 choice = input('>>:').strip()
    17 
    18 if __name__ == '__main__':
    19     if hasattr(d, choice):
    20         getattr(d, choice)
    21     else:
    22         setattr(d, choice, bulk)
    23         func = getattr(d, choice)
    24         func(d)
    25         delattr(d, choice)
    26         print(hasattr(d, choice))
    复制代码

     

    5、动态导入模块

    上面的例子是在某个特定的目录结构下才能正常实现的,也就是commons和visit模块在同一目录下,并且所有的页面处理函数都在commons模块内。如下图:

    但在现实使用环境中,页面处理函数往往被分类放置在不同目录的不同模块中,也就是如下图:

    难道我们要在visit模块里写上一大堆的import 语句逐个导入account、manage、commons模块吗?要是有1000个这种模块呢?

    刚才我们分析完了基于字符串的反射,实现了动态的函数调用功能,我们不禁会想那么能不能动态导入模块呢?这完全是可以的!

    python提供了一个特殊的方法:__import__(字符串参数)。通过它,我们就可以实现类似的反射功能。__import__()方法会根据参数,动态的导入同名的模块。

    复制代码
    >>> help(__import__)
    Help on built-in function __import__ in module builtins:
    
    __import__(...)
        __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.  Level 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.
    复制代码

    我们再修改一下上面的visit模块的代码。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        modules, func = inp.split('/')
        obj = __import__(modules)
        if hasattr(obj, func):
            func = getattr(obj, func)
            func()
        else:
            print('page not found 404...')
     
    if __name__ == '__main__':
        run()

    测试结果:

    1
    2
    3
    4
    5
    please put the website's url you want to access: commons/home
    this is home page of the website...
     
    please put the website's url you want to access: account/find
    this is searching page...

    我们来分析一下上面的代码:

      首先,我们并没有定义任何一行import语句;

      其次,用户的输入inp被要求为类似“commons/home”这种格式,其实也就是模拟web框架里的url地址,斜杠左边指向模块名,右边指向模块中的成员名。

      然后,modules,func = inp.split("/")处理了用户输入,使我们获得的2个字符串,并分别保存在modules和func变量里。

      接下来,最关键的是obj = __import__(modules)这一行,它让程序去导入了modules这个变量保存的字符串同名的模块,并将它赋值给obj变量。

      最后的调用中,getattr去modules模块中调用func成员的含义和以前是一样的。

      总结:通过__import__函数,我们实现了基于字符串的动态的模块导入。

      同样的,这里也有个小瑕疵!

      如果我们的目录结构是这样的:

     我们来分析一下上面的代码:

      首先,我们并没有定义任何一行import语句;

      其次,用户的输入inp被要求为类似“commons/home”这种格式,其实也就是模拟web框架里的url地址,斜杠左边指向模块名,右边指向模块中的成员名。

      然后,modules,func = inp.split("/")处理了用户输入,使我们获得的2个字符串,并分别保存在modules和func变量里。

      接下来,最关键的是obj = __import__(modules)这一行,它让程序去导入了modules这个变量保存的字符串同名的模块,并将它赋值给obj变量。

      最后的调用中,getattr去modules模块中调用func成员的含义和以前是一样的。

      总结:通过__import__函数,我们实现了基于字符串的动态的模块导入。

    同样的,这里也有个小瑕疵!

    如果我们的目录结构是这样的:

         

       

    那么在visit的模块调用语句中,必须进行修改,我们想当然地会这么做:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        modules, func = inp.split('/')
        obj = __import__('lib.' + modules)
        if hasattr(obj, func):
            func = getattr(obj, func)
            func()
        else:
            print('page not found 404...')
     
    if __name__ == '__main__':
        run()

    改了这么一个地方:obj = __import__("lib." + modules),看起来似乎没什么问题,和import lib.commons的传统方法类似,但实际上运行的时候会有错误。

    1
    2
    please put the website's url you want to access: commons/home
    page not found 404...

    为什么呢?因为对于lib.xxx.xxx.xxx这一类的模块导入路径,__import__默认只会导入最开头的圆点左边的目录,也就是“lib”。我们可以做个测试,在visit同级目录内新建一个文件,代码如下:

    1
    2
    obj = __import__("lib.commons")
    print(obj)

    执行结果:

    1
    <module 'lib' (namespace)>

    这个问题怎么解决呢?加上fromlist = True参数即可!

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    def run():
        inp = input("please put the website's url you want to access: ").strip()
        modules, func = inp.split('/')
        obj = __import__('lib.' + modules, fromlist=True)
        if hasattr(obj, func):
            func = getattr(obj, func)
            func()
        else:
            print('page not found 404...')
     
    if __name__ == '__main__':
        run()

    至此,动态导入模块的问题基本都解决了,只剩下最后一个,那就是万一用户输入错误的模块名呢?比如用户输入了somemodules/find,由于实际上不存在somemodules这个模块,必然会报错!那有没有类似上面hasattr内置函数这么个功能呢?答案是没有!碰到这种,你只能通过异常处理来解决。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
     
    '''visit.py'''
     
    def run():
        try:
            inp = input("please put the website's url you want to access: ").strip()
            modules, func = inp.split('/')
            obj = __import__('lib.' + modules, fromlist=True)
            if hasattr(obj, func):
                func = getattr(obj, func)
                func()
            else:
                print('page not found 404...')
        except Exception as e:
            print(e)
     
    if __name__ == '__main__':
        run()

    6、最后的思考

    可能有人会问python不是有两个内置函数exec和eval吗?他们同样能够执行字符串。比如:

    1
    2
    3
    >>> exec("print('hahha')")
    hahha
    >>>

    那么直接使用它们不行吗?非要那么费劲地使用getattr,__import__干嘛?

    其实,在上面的例子中,围绕的核心主题是如何利用字符串驱动不同的事件,比如导入模块、调用函数等等,这些都是python的反射机制,是一种编程方法、设计模式的体现,凝聚了高内聚、低耦合的编程思想,不能简单的用执行字符串来代替。当然,exec和eval也有它的舞台,在web框架里也经常被使用。

    参考了: http://www.cnblogs.com/feixuelove1009/p/5576206.html
    参考了:https://www.cnblogs.com/ant-colonies/p/6756014.html

  • 相关阅读:
    51Nod 1267 4个数和为0 二分
    51Nod 1090 3个数和为0 set 二分优化
    51Nod 1001 数组中和等于K的数对 Set
    Codeforces 890C
    Codeforces 890B
    Codeforces 890A
    51nod 1058 N的阶乘的长度 位数公式
    C#调用本机摄像头
    读取、写入excel数据
    数据库笔记--基本应用
  • 原文地址:https://www.cnblogs.com/qxh-beijing2016/p/13028297.html
Copyright © 2011-2022 走看看