[英]How to write python __init__.py file for module
If I have a module folder structure like this:如果我有这样的模块文件夹结构:
studio
tools
__init__.py
camera
__init__.py
camera.py
element
__init__.py
element.py
How do I write the __init__.py files to make it so I can write my import statements like the following?如何编写 __init__.py 文件来制作它,以便我可以编写如下导入语句? There is a class object in the
camera
module called CameraNode
that I would like to call like shown in the sample below.在名为
CameraNode
的camera
模块中有一个 class object,我想调用它,如下面的示例所示。
from studio import tools
tools.camera.fn()
tools.CameraNode('')
tools.element.fn()
If you have a studio/tools/ __init__.py
file like this:如果你有这样的 studio/tools/
__init__.py
文件:
from .camera import *
from .element import *
Then you can do a single import elsewhere like:然后您可以在其他地方进行一次导入,例如:
from studio import tools
and then reference everything as if it were directly in studio.tools.然后像直接在 studio.tools 中一样引用所有内容。
Not sure if this is answering your question exactly, but hopefully it gets you going in the right direction.不确定这是否准确地回答了您的问题,但希望它能让您朝着正确的方向前进。
An __init__py
file allows you to treat any directory as a python package. __init__py
文件允许您将任何目录视为 python package。 It is not necessary to write anything in the file itself, just creating it in your directory is enough.不需要在文件本身中写入任何内容,只需在您的目录中创建它就足够了。
So camera
, element
and tools
can behave as packages.所以
camera
, element
和tools
可以作为包。
However, if you want to access python files in sub-directories as well, then you must import those in the __init__.py
of the parent directory.但是,如果您还想访问子目录中的 python 文件,则必须在父目录的
__init__.py
中导入这些文件。
For example, if you want to do tools.camera
then you must import camera
in the __init__.py
in the tools directory.例如,如果你想做
tools.camera
那么你必须在 tools 目录下的__init__.py
中导入camera
。
Otherwise, you will have to import camera
separately to access all of the functions in it.否则,您必须单独导入
camera
才能访问其中的所有功能。
Hope this answers your question.希望这能回答你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.