python __import__动态模块

1.只限解释器内部自己使用。

条件:test.lianx_2.py中的代码:

class a(object):
    def __init__(self,name):
        self.name=name
    def c(self):
        print 'name:%s'%self.name
b=a('rr')
b.c()

结果:
name:rr

__import__动态模块:

d=__import__('test.lianx_2')  #只限解释器内部使用
print d
print d.lianx_2
f=d.lianx_2
f.b.c()  


结果:
name:rr
<module 'test' from 'C:\Users\xuxia\workspace\helloword\src\test\__init__.pyc'>
<module 'test.lianx_2' from 'C:\Users\xuxia\workspace\helloword\src\test\lianx_2.pyc'>
name:rr
import importlib   #官方使用
d=importlib.import_module('lianx_2')
print d.b.name

结果:
rr

猜你喜欢

转载自www.cnblogs.com/iexperience/p/9233430.html