[英]How can I import subpackage?
I have a file structure like this:我有这样的文件结构:
test.py
Dir1\
__init__.py
Something.py
Dir2\
__init__.py
Something2.py
#Dir1.__init__.py
from .Something import *
Dir2.__init__.py
have has the same code, but with.Something2 Dir2.__init__.py
具有相同的代码,但带有.Something2
Something.py has simple add method, Something2.py has simple sub method. Something.py 有简单的 add 方法,Something2.py 有简单的 sub 方法。
What I need:我需要的:
#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))
But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'
.但我得到一个错误AttributeError: module 'Dir1' has no attribute 'Dir2'
。
If I use from.Dir2 import *
in Dir1.__init__.py
code in test.py
works, but also works print(Dir1.sub(10, 14))
, what I don't want.如果我在test.py
中的Dir1.__init__.py
代码中使用from.Dir2 import *
可以工作,但print(Dir1.sub(10, 14))
也可以工作,这是我不想要的。 I tryed many variants, but they brought me to error or Dir1.sub
working.我尝试了许多变体,但它们给我带来了错误或Dir1.sub
工作。
This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer.这可能可以在互联网上找到,但是我的英语知识很糟糕,我可能会错过答案。 Of course I've already tried searching for it on the Internet.当然,我已经尝试在 Internet 上搜索它。
I will be very grateful for your answer.我将非常感谢您的回答。
# test.py
import Dir1.Dir2
print(Dir1.Dir2.sub(10,14))
Should work.应该管用。 Also if you need to you can rename modules at import using the as
keyword此外,如果您需要,您可以在导入时使用as
关键字重命名模块
import some_module as new_name
Probably it is crutch, but I found solve.可能是拐杖,但我找到了解决办法。 Now I have this file structure:现在我有了这个文件结构:
test.py
Dir1\
__init__.py
Dir1\
__init__.py
Something.py
Dir2\
__init__.py
Something2.py
#Dir1.__init__
import Dir1 as Add
from .Dir1 import Dir2 as Sub
And now I can use现在我可以使用
#test.py
import Dir1
print(Dir1.Sub.sub(10, 7))
And can't use并且不能使用
#test.py
import Dir1
print(Dir1.sub(10, 7))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.