動態加載模塊有三種方法
1,使用系統函數__import_()
stringmodule = __import__('string')
2,使用imp 模塊
import imp
stringmodule = imp.load_module('string',*imp.find_module('string'))
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')python
examples:shell
目錄結構: E: --aa ----__init__.py ----sort_heb1.py
sort_heb1.pyapp
# -*- coding: utf-8 -*- class a(): def b(self): print '1111'
E:\>python Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> sys.path.append("E:\\aa") >>> a=__import__('aa.sort_heb1') >>> dir(a) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'sort_heb1'] >>> ss=a.sort_heb1 >>> ss.b Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'b' >>> dir(ss) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a'] >>> a1=ss.a() >>> a1.b <bound method a.b of <aa.sort_heb1.a instance at 0x0000000001DA4648>> >>> a1.b() 1111 >>>