Python Import class in __init__.py from file in same package

只谈情不闲聊 提交于 2019-12-23 10:19:13

问题


I feel like I should know this, having programmed in Python for as long as I have, but I'm constantly learning new things about the fine lanuaguge. The question I have (which may very well be a duplicate, however I haven't been able to find this same case) is this. I have a file layout like this:

websocket/
    __init__.py
    client.py
    server.py

How can I import classes that are in the file __init__.py from client.py or server.py? Nice and simple :P Thanks in advance! My question isn't a duplicate of this because I am importing from inside the package, and at any rate, doing what the people did in the answer did not help at all.


回答1:


Names defined in a package __init__.py file are available as names in the package namespace itself.

Therefore, if you have a Connection class in your __init__ package, from inside the package you do import it the same way one making use of your package would: refer to it by the package name as in

from websocket import Connection

If for some reason your package is not configured in your pythonpath, or your directory name can change you can use a relative import - in that case, refer to the current package just as . that means that in your client.py you can just do:

from . import Connection


来源:https://stackoverflow.com/questions/31128333/python-import-class-in-init-py-from-file-in-same-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!