[英]Importing a function from another folder
Let's say I have a structure like this:假设我有这样的结构:
tests----------------
___init__.py
test_functions_a
functions-----------
___init__.py
functions_a
functions_b
I want to test a function from functions_a
, but inside functions_a
I am importing a function from functions_b
.我想从functions_a
测试 function ,但在functions_a
内部我从functions_b
导入 function 。
When I am trying:当我尝试时:
from functions.functions_a import function_aa
I am getting an error, because inside functions_a
I have a line:我收到一个错误,因为在functions_a
里面我有一行:
from functions_b import function_bb
and not:并不是:
from functions.functions_b import function_bb
How can I solve this?我该如何解决这个问题?
Any good practises are welcome, as I have no experience in structuring projects.欢迎任何好的做法,因为我没有构建项目的经验。
According to Google Python Style Guide , you should:根据Google Python 风格指南,您应该:
Use import statements for packages and modules only, not for individual classes or functions.仅对包和模块使用 import 语句,而不是单个类或函数。 Note that there is an explicit exemption for imports from the typing module.请注意,从类型模块导入有明确的豁免。
You should also:您还应该:
Import each module using the full pathname location of the module.使用模块的完整路径名位置导入每个模块。
If you follow those two conventions, you will probably avoid, in the future, situations like the one you just described.如果您遵循这两个约定,您将来可能会避免像您刚才描述的那样的情况。
Now, here's how your code will probably look like if you follow those tips:现在,如果您遵循这些提示,您的代码可能会如下所示:
Module functions.functions_a
:模块functions.functions_a
:
from functions import functions_b as funcs_b
def function_aa():
print("AA")
def function_aa_bb():
function_aa()
funcs_b.function_bb()
Module functions.functions_b
:模块functions.functions_b
:
def function_bb():
print("BB")
And, finally, test_functions_a.py
:最后, test_functions_a.py
:
from functions import functions_a as funcs_a
if __name__ == "__main__":
funcs_a.function_aa()
funcs_a.function_aa_bb()
Output: Output:
AA
AA
BB
You cannot directly import the function instead you could import File 1 to some other File and then call the function from that particular file you imported.您不能直接导入 function 而是可以将文件 1 导入其他文件,然后从您导入的特定文件中调用 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.