简体   繁体   English

Python 3:如何从包中的模块导入__init__.py?

[英]Python 3: How do I import __init__.py from a module in its package?

I'm on Python 3.7. 我使用的是Python 3.7。 I created a foo module, which has the following folder layout: 我创建了一个foo模块,它具有以下文件夹布局:

foo/
    __init__.py

I put all the code for the foo package in the __init__.py file. 我将foo软件包的所有代码都放在__init__.py文件中。 I'm able to run import foo from other scripts as normal. 我可以正常运行其他脚本中的import foo

Later on, I wanted to add a util.py file to this package. 稍后,我想向该软件包添加一个util.py文件。 The folder layout became: 文件夹布局变为:

foo/
    __init__.py
    util.py

My question is: Inside util.py , I'd like to access the classes, functions, etc. defined in __init__.py . 我的问题是:在util.py中 ,我想访问__init__.py中定义的类,函数等。 How can I "import" __init__.py from the util.py file? 如何从util.py文件中“导入” __init__.py Is this even possible? 这有可能吗? If I have to rearrange my code, then how? 如果必须重新排列我的代码,那怎么办?

I've tried to add the following to util.py : 我尝试将以下内容添加到util.py中

from . import __init__
print(__init__.some_var_in_init)

But I get this error message: 但我收到此错误消息:

Traceback (most recent call last):
  File "util.py", line 3, in <module>
    print(__init__.some_var_in_init)
AttributeError: 'method-wrapper' object has no attribute 'some_var_in_init'

So I'm guessing that's not the way to go about it. 所以我想这不是解决之道。

import foo可以正常工作。

I found the answer. 我找到了答案。 It isn't enough to add import foo , but the parent folder must be added as well: 添加import foo是不够的,但是还必须添加父文件夹:

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import foo
print(foo.some_var_in_init)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM