Python 任意文件夹中的子包。 __init__.py怎么写?
Python subpackage in arbitrary folder. How to write the __init__.py?
如果我有这个层级
A
|- __init__.py
|-B
|- __init__.py
|- funcitons.py
(which contains def my_function(): pass)
并且我安装了软件包 A
,我可以执行以下操作
from A.B import functions
functions.my_function()
或
from A.B.functions import my_function
my_function()
如果B被封装在多个子文件夹(不是包)中,如何实现相同的结果?
正如 Antti Haapala 所建议的,在 Python 2 中,这就是 __path__
的用途。以下 A/__init__.py
完成了这项工作。
import os
__path__.append( os.path.join(os.path.dirname(__file__), 'res/path'))
另见 What is __path__ useful for?
如果我有这个层级
A
|- __init__.py
|-B
|- __init__.py
|- funcitons.py
(which contains def my_function(): pass)
并且我安装了软件包 A
,我可以执行以下操作
from A.B import functions
functions.my_function()
或
from A.B.functions import my_function
my_function()
如果B被封装在多个子文件夹(不是包)中,如何实现相同的结果?
正如 Antti Haapala 所建议的,在 Python 2 中,这就是 __path__
的用途。以下 A/__init__.py
完成了这项工作。
import os
__path__.append( os.path.join(os.path.dirname(__file__), 'res/path'))
另见 What is __path__ useful for?