Chinaunix首页 | 论坛 | 博客
  • 博客访问: 129589
  • 博文数量: 32
  • 博客积分: 115
  • 博客等级: 民兵
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-30 23:19
个人简介

The minute you think of giving up, think of the reason why you held on so long!

文章分类

全部博文(32)

文章存档

2018年(4)

2016年(8)

2015年(2)

2014年(11)

2013年(6)

2012年(1)

我的朋友

分类: Python/Ruby

2018-04-10 16:37:00

__import__ 模块为Python的内置模块,可以动态(字符串方式)加载其他类、函数、模块!

1、加载同层目录下的模块功能(同一个包下的其他功能函数)
    main.py和test_demo.py 都在同一个层目录(p_test目录)下

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_

  3. #test_demo.py 文件

  4. def test():
  5.     print 'test demo!!!'
    动态的加载方式

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 

  3. #main.py 文件

  4. model = __import__('test_demo')    
  5. func = getattr(model, 'test')
  6. func()
    正常的加载方式

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_

  3. #main.py 文件

  4. import test_demo
  5. test_demo.test()

2、加载其他模块功能(其他包下的功能函数)
    main.py(p_test目录下)和test_demo.py (demo目录下)不在同一个层目录下

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_

  3. #test_demo.py 文件

  4. def test():
  5.     print 'test'
    动态加载方式

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_

  3. #main.py 文件

  4. model = __import__('demo.'+'test_demo')
  5. method = getattr(model, 'test_demo')
  6. func = getattr(method, 'test')
  7. func()
    正常加载方式

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_

  3. #main.py 文件

  4. import demo.test_demo
  5. demo.test_demo.test()
  6. 或者
  7. from demo import test_demo
  8. test_demo.test()

__import__ 相关的还有四个内置函数:getattr(获取)、setattr(设置)、hasattr(检查)、delattr(删除),学懂了再来补充记录。




阅读(1290) | 评论(0) | 转发(0) |
0

上一篇:python学习--2_2

下一篇:没有了

给主人留下些什么吧!~~