本文实例总结了python动态加载包的方法。分享给大家供大家参考,具体如下:
动态加载模块有三种方法
1. 使用系统函数__import_()
1
|
stringmodule = __import__ ( 'string' ) |
2. 使用imp 模块
1
2
3
|
import imp stringmodule = imp.load_module( 'string' , * imp.find_module( 'string' )) imp.load_source( "TYACMgrHandler_" + app.upper(), filepath) |
3. 用exec
1
2
|
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')
动态增加属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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() |
动态载入包:
1
2
3
4
5
6
7
8
|
def test(s,e): print s print e class C(): def __init__( self ,name): print name def test( self ): print 'class!!!' |
加载器代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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!' ) |
根据名字加载指定文件
1
2
3
4
5
|
def loadapp( self , app): filepath = "mgr/" + app + ".py" if os.path.exists(filepath): imp.load_source( "TYACMgrHandler_" + app.upper(), filepath) / / 修改了app.py,从新调用这个函数,新的代码自动生效 |
根据名字调用对应方法
1
2
|
return getattr ( self , op)(args.get( "port" ), args) / / op = "start" args = dict getattr ( self , self .request.method.lower())( * args, * * kwargs) |
希望本文所述对大家Python程序设计有所帮助。