[英]How to import variables defined in __init__.py?
I'm a little confused about how importing works. 我对导入工作有点困惑。 Assume: 假设:
package/
__init__.py
file1.py
In __init__.py
: 在__init__.py
:
from file1 import AClass
__version__ = '1.0'
In file1.py
: 在file1.py
:
Class AClass(object):
def bar():
# I want to use __version__here, but don't want to pass
# it through the constructor. Is there any way?
pass
If I use from . import __version__
如果我使用from . import __version__
from . import __version__
in file1.py
it just says ImportError: cannot import name __version__
. 在file1.py
from . import __version__
只是说ImportError: cannot import name __version__
。
You've got a circular dependency because both files try to import
each other. 你有一个循环依赖,因为两个文件都试图互相import
。 Move __version__
to a separate module, say package/version.py
, then import that in both others with 将__version__
移动到一个单独的模块,比如package/version.py
,然后将其导入到其他模块中
from .version import __version__
Try: 尝试:
__version__ = '1.0'
from file1 import AClass
You need to assign the constants before you import the module so that it'll be in place when you try to import it. 您需要在导入模块之前分配常量,以便在尝试导入模块时它就位。
EDIT: larsmans suggestion to avoid the circular dependency is a good idea. 编辑: larsmans建议避免循环依赖是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.