自学Python--反射

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41402059/article/details/82695104

反射:多用于网络编程

反射就是通过字符串的形式,导入模块;通过字符串的形式,去模块寻找指定函数,并执行。利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!

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

猜你喜欢

转载自blog.csdn.net/weixin_41402059/article/details/82695104