Python error: AttributeError: 'module' object has no attribute

前端 未结 4 1275
梦如初夏
梦如初夏 2020-11-29 07:15

I\'m totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different... I have created a package (or so

相关标签:
4条回答
  • 2020-11-29 07:39

    More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

    Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

    >>> import lib
    >>> dir(lib)
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
    >>> import lib.pkg1
    >>> import lib.pkg1.mod11
    >>> lib.pkg1.mod11.mod12()
    mod12
    

    An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

    >>> from lib.pkg1 import mod11
    

    Then reference the function as simply mod11.mod12().

    0 讨论(0)
  • 2020-11-29 07:41

    The way I would do it is to leave the __ init__.py files empty, and do:

    import lib.mod1.mod11
    lib.mod1.mod11.mod12()
    

    or

    from lib.mod1.mod11 import mod12
    mod12()
    

    You may find that the mod1 dir is unnecessary, just have mod12.py in lib.

    0 讨论(0)
  • 2020-11-29 07:50

    When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

    If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

    If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

    0 讨论(0)
  • 2020-11-29 07:55

    My solution is put those imports in __init__.py of lib:

    in file: __init__.py
    import mod1
    

    Then,

    import lib
    lib.mod1
    

    would work fine.

    0 讨论(0)
提交回复
热议问题