• 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 * ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。

    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    transition过渡效果
    transform旋转变换效果
    让字体在div容器中垂直居中
    背景图片浮动居中
    解决图片浮动调节不了的问题(使用vertical-align属性)
    box-shadow向元素添加阴影效果
    hr中间插入字体
    codeforces 659D . Bicycle Race 几何
    codeforces 659E . New Reform 强连通
    codeforces 552 E. Vanya and Brackets 表达式求值
  • 原文地址:https://www.cnblogs.com/graceting/p/3620967.html
Copyright © 2020-2023  润新知