python動態載入包的方法小結

2022-09-28 09:00:13 字數 2182 閱讀 6651

動態載入模組有三種方法

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

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

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動態載入包

動態載入模組有三種方法 1,使用系統函式 import stringmodule import string 2,使用imp 模組 import imp stringmodule imp.load module string imp.find module string 3,使用exec impor...

python動態載入包

分類 python 2011 09 14 22 18 1684人閱讀收藏 舉報python import string list class module 動態載入模組有三種方法 1,使用系統函式 import stringmodule import string 2,使用imp 模組 import...

python 動態載入的實現方法

指令碼語言都有乙個優點,就是動態載入。lua語言有這個優點,python也有這個特性。說簡單點就是,如果開發者發現自己的 有bug,那麼程式設計客棧他可以在不關閉原來 的基礎之上,動態替換模組。替換方法一般用reload來完成。1 reload的基本原理 reload主要做了兩個動作,刪除原來的模組...