zoukankan      html  css  js  c++  java
  • 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:Python27libUserDict.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>
        FunctionType
    NameError: 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 * ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。

    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    Sql server char,nchar,varchar与Nvarchar的区别
    关于sysprocesses表各字段的作用
    多台子服务器更新中央服务器
    [转自MSDN]根据FxCop整理的.NET代码编写规范
    【原】Winfrom的自动更新模块
    Silverlight 3和Expression 3将于7月10日发布
    【转蝈蝈俊.net 】SQL Server 2005 配置发送邮件
    WF4.0 RC 官方示例
    [转]Ubuntu Server下如何安装图形界面?
    [原]linux下如何查看本机IP,gateway,DNS
  • 原文地址:https://www.cnblogs.com/graceting/p/3620967.html
Copyright © 2011-2022 走看看