python动态加载包的方法小结

yipeiwu_com5年前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程序设计有所帮助。

相关文章

Python异常处理例题整理

Python异常处理例题整理

什么是异常? 异常是Python对象,表示一个错误。当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。在程序运行过程中,总会遇到各种各样的错误,有的错误是程序编写有问题...

Python操作Mongodb数据库的方法小结

本文实例讲述了Python操作Mongodb数据库的方法。分享给大家供大家参考,具体如下: 一 导入 pymongo from pymongo import MongoClient...

Python中Random和Math模块学习笔记

由于最近经常使用到Python中random,math和time``datetime模块, 所以决定花时间系统的学习一下 1. math模块 math中的函数不可以用于太过复杂的数的运算...

Python 通过调用接口获取公交信息的实例

如下所示: # -*- coding: utf-8 -*- import sys, urllib, urllib2, json city=urllib.quote(sys.argv...

python numpy数组复制使用实例解析

这篇文章主要介绍了python numpy数组复制使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用python时我们...