Understanding python imports

后端 未结 3 1776
有刺的猬
有刺的猬 2021-01-06 21:10

In the process of learning Django and Python. I can\'t make sense of this.

(Example Notes:\'helloworld\' is the name of my project. It has 1 app called \'app\'.)

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 21:55

    Python imports can import two different kinds of things: modules and objects.

    import x
    

    Imports an entire module named x.

    import x.y
    

    Imports a module named y and it's container x. You refer to x.y.

    When you created it, however, you created this directory structure

    x
        __init__.py
        y.py
    

    When you add to the import statement, you identify specific objects to pull from the module and move into the global namespace

    import x # the module as a whole
    x.a # Must pick items out of the module
    x.b
    
    from x import a, b # two things lifted out of the module
    a # items are global
    b
    

    If helloworld is a package (a directory, with an __init__.py file), it typically doesn't contain any objects.

    from x import y # isn't sensible
    import x.y # importing a whole module.
    

    Sometimes, you will have objects defined in the __init__.py file.

    Generally, use "from module import x" to pick specific objects out of a module.

    Use import module to import an entire module.

提交回复
热议问题