欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python動(dòng)態(tài)加載包的方法小結(jié)

 更新時(shí)間:2016年04月18日 11:33:15   作者:anghlq  
這篇文章主要介紹了python動(dòng)態(tài)加載包的方法,結(jié)合實(shí)例形式總結(jié)分析了Python動(dòng)態(tài)加載模塊,動(dòng)態(tài)增加屬性及動(dòng)態(tài)加載包的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例總結(jié)了python動(dòng)態(tài)加載包的方法。分享給大家供大家參考,具體如下:

動(dòng)態(tài)加載模塊有三種方法

1. 使用系統(tǒng)函數(shù)__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')

動(dòng)態(tài)增加屬性

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()

動(dòng)態(tài)載入包:

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!')

根據(jù)名字加載指定文件

def loadapp(self, app):
    filepath="mgr/"+app+".py"
    if os.path.exists(filepath):
      imp.load_source("TYACMgrHandler_"+app.upper(), filepath)
//修改了app.py,從新調(diào)用這個(gè)函數(shù),新的代碼自動(dòng)生效

根據(jù)名字調(diào)用對(duì)應(yīng)方法

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

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論