Python在同一包中的文件__init__.py中导入类 [英] Python Import class in __init__.py from file in same package
问题描述
我觉得我应该知道这一点,只要我有Python编程,但我不断学习关于精细语言的新东西。我有这个问题(可能很复杂,但我找不到同样的情况)就是这个问题。我有这样的文件布局:
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
如何导入文件中的类__init __。py
来自 client.py
或 server.py
?很好,很简单:P提前谢谢!我的问题不是这个的重复,因为我是从包内导入的,无论如何,做人们在答案中所做的事并没有帮助所有。
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.
推荐答案
在包 __ init __。py
文件中定义的名称是在包名称空间本身中作为名称提供。
Names defined in a package __init__.py
file are available as names in the package namespace itself.
因此,如果您的<$ c中有 Connection
类$ c> __ init __ 包,从包装内部导入它的方式与使用包装的方式相同:按包装名称引用,如
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
如果是某些原因你的包没有在你的pythonpath中配置,或你的目录名可以改变你可以使用相对导入 - 在这种情况下,请参考当前包,就像。
那样意味着在 client.py
中你可以这样做:
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
这篇关于Python在同一包中的文件__init__.py中导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!