zoukankan      html  css  js  c++  java
  • python中反射(__import__和getattr使用)

    反射:

    1、可通过字符串的形式导入模块

      1.1、单层导入 


     __import__('模块名')

      1.2、多层导入

     __import__(' list.text.commons',fromlist=True) #如果不加上fromlist=True,只会导入list目录

    2、可以通过字符串的形式执行模块的功能


     import glob,os
     
     modules = []
     for module_file in glob.glob("*-plugin.py"):
         try:
            module_name,ext = os.path.splitext(os.path.basename(module_file))
            module = __import__(module_name)
            modules.append(module)
         except ImportError:
             pass #ignore broken modules
          #say hello to all modules
          for module in modules:
             module.hello()
     

     def getfunctionbyname(module_name,function_name):
         module = __import__(module_name)
         return getattr(module,function_name)

    3、反射即想到4个内置函数分别为:getattr、hasattr、setattr、delattr  获取成员、检查成员、设置成员、删除成员下面逐一介绍先看例子:


     
     class Foo(object):
     
         def __init__(self):
          self.name = 'abc'
    
        def func(self):
            return 'ok'
      
     obj = Foo()
     #获取成员1 ret = getattr(obj, 'func')#获取的是个对象
     r = ret()
     print(r)
     #检查成员
     ret = hasattr(obj,'func')#因为有func方法所以返回True
     print(ret)
     #设置成员
     print(obj.name) #设置之前为:abc
     ret = setattr(obj,'name',19)
    20 print(obj.name) #设置之后为:19
    21 #删除成员
    22 print(obj.name) #abc
    23 delattr(obj,'name')
    24 print(obj.name) #报错
     
     

     
     
  • 相关阅读:
    MyBatis+MySQL 返回插入的主键ID
    微信被动回复用户消息-文本消息-springmvc环境下自动生成xml
    微信自动回复消息示例
    微信自定义菜单
    微信获取二维码
    微信被动回复用户消息-文本消息-填坑
    微信获得access-token
    设置ckeditor的高度
    Java三行代码搞定MD5加密
    Highchart
  • 原文地址:https://www.cnblogs.com/geogre123/p/10113819.html
Copyright © 2011-2022 走看看