Use 'import module' or 'from module import'?

前端 未结 19 2129
一向
一向 2020-11-21 07:47

I\'ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I\'ve just started with Python and I\'m

19条回答
  •  温柔的废话
    2020-11-21 07:55

    Here is another difference not mentioned. This is copied verbatim from http://docs.python.org/2/tutorial/modules.html

    Note that when using

    from package import item
    

    the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

    Contrarily, when using syntax like

    import item.subitem.subsubitem
    

    each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

提交回复
热议问题