Python面试题之Python反射详解

时间:2023-03-10 01:05:56
Python面试题之Python反射详解

0x00 前言

反射,可以理解为利用字符串的形式去对象中操作成员属性和方法

反射的这点特性让我联想到了exec函数,也是把利用字符串的形式去让Python解释器去执行命令

Python Version: 3.5+

解释Python的反射,先提一个简单的需求,现在我有一个简易的网站,由两个文件组成,一个是具体执行操作的commons.py文件,一个是入口文件index.py,现在我需要在入口文件中设置,让用户输入url,根据用户输入的url去后端执行相应的操作,内容如下:

# commons.py
def login():
print('登录页面!') def logout():
print('退出页面!') def index():
print('主页面')
# index.py
import commons inp = input('url > ') if inp == 'login':
commons.login()
elif inp == 'logout':
commons.logout()
elif inp == 'index':
commons.index()
else:
print('') ------------
url > login
登录页面!

上面我使用了if判断,根据每一个url请求去后端执行指定的函数。那现在我的网站内容变多了,在commons.py中有100个页面操作,那么相对应的我在index.py中也要使用if else 对这100个页面函数进行手动指定。

有了Python