反射:多用于网络编程
反射就是通过字符串的形式,导入模块;通过字符串的形式,去模块寻找指定函数,并执行。利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
hasattr和getattr:
class Info:
infos = {'teachers':'teachers infos', 'students':'students infos'}
def show_student(self):
print('show_student')
def show_teacher(self):
print('show_teacher')
@classmethod
def func(cls):
print('classmethod')
print(hasattr(Info, 'test')) # False
if hasattr(Info, 'infos'):
res = getattr(Info, 'infos')
print(res) # {'teachers': 'teachers infos', 'students': 'students infos'}
if hasattr(Info, 'func'):
res = getattr(Info, 'func') # 类方法内存地址
res() # classmethod
=========================================================================================
class Info:
infos = {'teachers':'show_teacher', 'students':'show_student'}
def show_student(self):
print('show_student')
def show_teacher(self):
print('show_teacher')
@classmethod
def func(cls):
print('classmethod')
info = Info()
if hasattr(info, 'infos'):
res = getattr(info, 'infos')
for i in res:
if hasattr(info, res[i]):
getattr(info, res[i])() # show_teacher show_student
反射模块时第一个参数为模块名
反射自己模块时:
import sys
def f():
print('f')
current_module = sys.modules[__name__] # 获取本模块对象
res = getattr(current_module, 'f')
res() # f
设置修改变量:setattr
删除变量:delattr