自学Python--反射

反射:多用于网络编程

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值