[英]Python3 relative imports
I'm tired of reading one-off use cases of relative imports so I figured I'd as a question to get an example of how to do a relative import from a directory above and bellow , for both importing module functions and class objects. 我已经厌倦了阅读相对导入的一次性用例,因此我想作为一个问题来举例说明如何从上层和下面的目录中进行相对导入,以同时导入模块函数和类对象。
directory structure: 目录结构:
.
├── lib
│ ├── __init__.py
│ └── bar.py
└── src
├── main.py
└── srclib
├── __init__.py
└── foo.py
bar.py bar.py
def BarFunc():
print("src Bar function")
class BarClass():
def __inti__(self):
print("src Bar Class")
def test(self):
print("BarClass working")
foo.py foo.py
def FooFunction():
print("srclib Foo function")
class FooClass():
def __init__(self):
print("srclib Foo Class")
def test(self):
print("FooClass working")
Question: What is the syntax in python 3 to import for these use cases? 问题:在这些用例中导入的python 3的语法是什么?
main.py main.py
# What is the syntax to import in python 3?
# I want to be able to call FooFunc()
foo.FooFunc()
# I want to be able to create a FooClass() object
foo_class = foo.FooClass()
foo_class.test()
# I want to be able to call FooFunc()
bar.BarFunc()
# I want to be able to create a BarClass() object
bar_class = bar.BarClass()
bar_class.test()
It all depends on where you start your python
interpreter from. 这完全取决于您从何处启动
python
解释器。 In your case, I would suggest you to start the interpreter from your project's root directory while making the following changes: 对于您的情况,我建议您从项目的根目录启动解释器,同时进行以下更改:
In file src/srclib/__init__.py
add: 在文件
src/srclib/__init__.py
添加:
from . import foo
The reason for doing this is to explicitly state in your __init__.py
file what to import from your module. 这样做的原因是在
__init__.py
文件中明确说明要从模块导入的内容。
In your main.py
file, add the following: 在您的
main.py
文件中,添加以下内容:
from lib import bar
from src.srclib import foo
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.