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

1、前言

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

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

 

2、web实例

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

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

#!/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模块,作为程序入口,接受用户输入,展示相应的页面,代码如下:(这段代码是比较初级的写法)

#!/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()

运行结果如下:

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修改一下,代码如下:

#!/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.
help(getattr)

相关文章:

  • 2022-12-23
  • 2021-09-30
  • 2022-12-23
  • 2021-10-20
  • 2021-05-21
  • 2022-12-23
  • 2022-02-16
  • 2022-02-20
猜你喜欢
  • 2022-12-23
  • 2021-12-03
  • 2021-07-14
  • 2021-11-26
  • 2021-07-27
  • 2022-12-23
相关资源
相似解决方案