python动态加载包的方法小结

yipeiwu_com6年前Python基础

本文实例总结了python动态加载包的方法。分享给大家供大家参考,具体如下:

动态加载模块有三种方法

1. 使用系统函数__import_()

stringmodule = __import__('string')

2. 使用imp 模块

import imp 
stringmodule = imp.load_module('string',*imp.find_module('string'))
imp.load_source("TYACMgrHandler_"+app.upper(), filepath)

3. 用exec

import_string = "import string as stringmodule"
exec import_string

变量是否存在

1. hasattr(Test,'t')
2. 'var'   in   locals().keys()
3. 'var'   in   dir()
4. vars().has_key('s')

动态增加属性

class Obj(object):
  pass
def main():
  list=["a","b", "c"]
  for i inrange(1,len(list),2):
    Obj = type('Obj',(),{list[i]:lambdaself,s:obj.__setattr__(s.split(" = ")[0],s.split(" = ")[1])})
  obj =Obj()
  for i inrange(0,len(list),2):
    obj.__setattr__(list[i],list[i])  
  obj.a =1
  obj.b("a =2")
  obj.b("c =3")
  printobj.a
  printobj.c
if __name__ == '__main__':
  main()

动态载入包:

def test(s,e):
  print s
  print e
class C():
  def __init__(self,name):
    print name
  def test(self):
    print 'class!!!'

加载器代码:

class Dynload():
  def __init__(self,package,imp_list):
    self.package=package
    self.imp=imp_list
  def getobject(self):
    return __import__(self.package,globals(),locals(),self.imp,-1)
  def getClassInstance(self,classstr,*args):
    return getattr(self.getobject(),classstr)(*args)  
  def execfunc(self,method,*args):
    return getattr(self.getobject(),method)(*args)
  def execMethod(self,instance,method,*args):
    return getattr(instance,method)(*args)
#Test:
dyn=Dynload('util.common',['*'])
ins=dyn.getClassInstance('C','gao')
dyn.execMethod(ins,'test')
dyn.execfunc('test','Hello','function!')

根据名字加载指定文件

def loadapp(self, app):
    filepath="mgr/"+app+".py"
    if os.path.exists(filepath):
      imp.load_source("TYACMgrHandler_"+app.upper(), filepath)
//修改了app.py,从新调用这个函数,新的代码自动生效

根据名字调用对应方法

return getattr(self, op)(args.get("port"), args) //op="start" args=dict
getattr(self, self.request.method.lower())(*args, **kwargs)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python3日期与时间戳转换的几种方法详解

日期和时间的相互转换可以利用Python内置模块 time 和 datetime 完成,且有多种方法供我们选择,当然转换时我们可以直接利用当前时间或指定的字符串格式的时间格式。 获取当前...

Laravel框架表单验证格式化输出的方法

Laravel框架表单验证格式化输出的方法

最近在公司的项目开发中使用到了 laravel 框架,采用的是前后端开发的模式。接触过前后端开发模式的小伙伴应该都知道,后端返回的数据格式需要尽可能搞得保证一致性,这样前端在处理时也方...

Python中logging.NullHandler 的使用教程

在使用 peewee 框架时,默认是不会出现日志消息的。 from peewee import Model, CharField, DateTimeField, IntegerFie...

tensorflow训练中出现nan问题的解决

深度学习中对于网络的训练是参数更新的过程,需要注意一种情况就是输入数据未做归一化时,如果前向传播结果已经是[0,0,0,1,0,0,0,0]这种形式,而真实结果是[1,0,0,0,0,0...

Python标准库sched模块使用指南

事件调度 sched 模块内容很简单,只定义了一个类。它用来最为一个通用的事件调度模块。 class sched.scheduler(timefunc, delayfunc) 这个类定义...