Python_两种导入模块的方法异同
来源:互联网 发布:淘宝网店实战宝典txt 编辑:程序博客网 时间:2024/06/12 20:47
Python_两种导入模块的方法异同
Python中有两种导入模块的方法
1:import module
2:from module import *
使用from module import *方法可以导入独立的项,也可以用from module import *导入所有的东西。eg:from types import FunctionType
代码示例:
>>> from UserDict import UserDict>>> UserDict<class UserDict.UserDict at 0x015D3B90>>>> import UserDict>>> UserDict<module 'UserDict' from 'C:\Python27\lib\UserDict.pyc'>
在上面,使用from UserDict import UserDict进行模块的导入,UserDict 被直接导入到局部名字空间去了,所以它可以直接使用,而不需要加上模块名的限定。
再比如:
>>> import types>>> types.FunctionType ##1.types 模块不包含方法,只是表示每种 Python 对象类型的属性。注意这个属性必需用模块名 types 进行限定。<type 'function'>>>> FunctionType ##2.FunctionType 本身没有被定义在当前名字空间中;它只存在于 types 的上下文环境中。Traceback (most recent call last): File "<pyshell#116>", line 1, in <module> FunctionTypeNameError: name 'FunctionType' is not defined>>> from types import FunctionType ##3.这个语法从 types 模块中直接将 FunctionType 属性导入到局部名字空间中>>> FunctionType ##4.FunctionType 可以直接使用,与 types 无关<type 'function'>
总结:什么时候你应该使用 from module import?
- 如果你要经常访问模块的属性和方法,且不想一遍又一遍地敲入模块名,使用 from module import。
- 如果你想要有选择地导入某些属性和方法,而不想要其它的,使用 from module import。
- 如果模块包含的属性和方法与你的某个模块同名,你必须使用 import module 来避免名字冲突。
但是要注意的是:尽量少用 from module import * ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。
阅读全文
0 0
- Python_两种导入模块的方法异同
- Python模块在使用中的两种导入方法
- 初始化String的两种方法有何异同
- IronPython 与 c# 交互之导入Python模块的两种方法
- python根据路径导入模块的两种方法:sys.path.append和imp.load_source
- 导入mdf文件的两种方法
- 导入导出数据库的两种方法
- Excel导入DataTable的两种方法
- python导入模块的4种方法
- python导入模块的4种方法
- python导入模块的三种方法
- python_模块
- Python_模块
- Js_log2000_两种定时器的异同
- Python导入模块的方法
- python导入模块的方法
- Python模块的导入方法
- [Hibernate]spring整合hibernate扫描实体类的两种方法annotatedClasses和packagesToScan的异同
- oracle 还原数据库 imp
- AFNetWorking
- 多线程编程10例问题(3)
- ERROR server: 192.168.20.175:22122, response status 2 != 0
- Java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the
- Python_两种导入模块的方法异同
- CodeForces 831A-Unimodal Array
- TEST
- 牛顿迭代法算近似平方根
- node-开始
- Java多线程____Volatile使用和原理
- Lucene--全文检索的基本原理
- CodeFroces 831B. Keyboard Layouts(构造题)
- 判断一个链表是否为回文结构