python 导入包 init_Python在同一包中的文件__init__.py中导入类

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.

解决方案

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 tha case, refer to the current package just as . that means that in your client.py you can just do:

from . import Connection

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值