python: Two modules and classes with the same name under different packages

前端 未结 3 698
孤城傲影
孤城傲影 2020-12-13 05:00

I have started to learn python and writing a practice app. The directory structure looks like

src
 |
 --ShutterDeck
    |
    --Helper
       |
       --User         


        
相关标签:
3条回答
  • 2020-12-13 05:03

    You want to import the User modules in the package __init__.py files to make them available as attributes.

    So in both Helper/__init_.py and Controller/__init__.py add:

    from . import User
    

    This makes the module an attribute of the package and you can now refer to it as such.

    Alternatively, you'd have to import the modules themselves in full:

    import ShutterDeck.Controller.User
    import ShutterDeck.Helper.User
    
    u1=ShutterDeck.Controller.User.User()
    u2=ShutterDeck.Helper.User.User()
    

    so refer to them with their full names.

    Another option is to rename the imported name with as:

    from ShutterDeck.Controller import User as ControllerUser
    from ShutterDeck.Helper import User as HelperUser
    
    u1 = ControllerUser.User()
    u2 = HelperUser.User()
    
    0 讨论(0)
  • 2020-12-13 05:10

    This might also help (struggled with similar problem today):

    ShutterDeck
    ├── Controller
    │   ├── __init__.py
    │   └── User.py
    ├── Helper
    │   ├── __init__.py
    │   └── User.py
    └── __init__.py
    

    in ShutterDeck/{Controller,Helper}/__init__.py:

    from .User import User
    

    And then:

    >>> import ShutterDeck.Helper
    >>> helperUser = ShutterDeck.Helper.User()
    >>> helperUser
    <ShutterDeck.Helper.User.User object at 0x1669b90>
    >>> import ShutterDeck.Controller
    >>> controllerUser = ShutterDeck.Controller.User()
    >>> controllerUser
    <ShutterDeck.Controller.User.User object at 0x1669c90>
    
    0 讨论(0)
  • 2020-12-13 05:23

    One way is just:

    import ShutterDeck.Controller.User
    import ShutterDeck.Helper.User
    
    cuser = ShutterDeck.Controller.User.User()
    huser = ShutterDeck.Helper.User.User()
    

    You can also do this:

    from ShutterDeck.Controller.User import User as ControllerUser
    from ShutterDeck.Helper.User import User as HelperUser
    
    0 讨论(0)
提交回复
热议问题