Python import statement semantics

后端 未结 3 1439
小蘑菇
小蘑菇 2021-02-13 03:54

I\'m having difficulty understanding the import statement and its variations.

Suppose I\'m using the lxml module for scraping websites.

The followin

3条回答
  •  我寻月下人不归
    2021-02-13 04:32

    Let's take an example of a package pkg with two module in it a.py and b.py:

    --pkg
       |
       | -- a.py
       |
       | -- b.py
       |
       | -- __init__.py
    

    in __init__.py you are importing a.py and not b.py:

    import a

    So if you open your terminal and do:

    >>> import pkg
    >>> pkg.a
    >>> pkg.b
    AttributeError: 'module' object has no attribute 'b'
    

    As you can see because we have imported a.py in pkg's __init__.py, we was able to access it as an attribute of pkg but b is not there, so to access this later we should use:

    >>> import pkg.b   # OR: from pkg import b
    

    HTH,

提交回复
热议问题