简体   繁体   English

导入多个子目录/模块,就好像它们只是一个模块一样

[英]Import multiple subdirectories/modules as if they are just one module

so I have a module/directory called A and it has init .py file and in it, it has another module/directory called B which have its init .py and a file called function.py which has a function called dummy()所以我有一个名为 A 的模块/目录,它有一个init .py 文件,其中有另一个名为 B 的模块/目录,它有它的init .py 和一个名为 function.py 的文件,它有一个名为 dummy() 的函数

here is the structure of directories这是目录的结构

A
|-- __init__.py
|
|-- B
    |
    |-- __init__.py
    |-- function.py

so what I want is to be on the same directory that contains directory A and do that所以我想要的是在包含目录 A 的同一目录中并执行此操作

from A import *
dummy()

what I have done is do that in B/ init .py我所做的是在 B/ init .py 中做到这一点

from dummy import *

and that in A/ init .py而在 A/ init .py 中

import B

and I can do that我可以做到

from A.B import *

I want to write A instead of AB我想写A而不是AB

I changed your import code a bit and it seems to work now like you wanted.我稍微更改了您的导入代码,现在似乎可以如您所愿。 So in the B directory's init.py it has:所以在 B 目录的 init.py 中它有:

# __init__.py in B
from .function import *

In the A directory's init.py:在A目录的init.py中:

# __init__.py in A
from .B import *

Now, when I run Python shell in the directory that contains A and and use from A import * , it calls dummy() with no problem.现在,当我在包含 A 的目录中运行 Python shell 并使用from A import * ,它调用dummy()没有问题。

However, there are discussions on using wildcard imports in Python.但是,有关于在 Python 中使用通配符导入的讨论。 Check this post for example: Should wildcard import be avoided?例如查看这篇文章: 是否应该避免通配符导入?

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

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