python from .xxx import yyy 与 from xxx import yyy区别

相对导入只能用于同一个package里,并且包内的文件不能单独运行,只能在包的外部来调用



|--testmodule.py
|
|--testpy
   |
   |-- __init__.py 模块标志文件
   |
   |-- hello.py    模块1
   |
   |-- test.py             模块2,导入模块1,不可以单独运行
   |
   |-- test2.py    可以单独运行




hello.py
print('hello.py')
class hhh():
    print('hhhh')



test.py
from .hello import hhh
print('test.py')



testmodule.py
from testpy import test
print('OK')


python3 testmodule.py
hello.py
hhhh
test.py
OK




test2.py
from hello import hhh
print('test2.py')


cd testpy 

ls
__init__.py	__pycache__	hello.py	test.py		test2.py

python3 test.py  不可以单独运行

Traceback (most recent call last):
  File "/Users/yourname/Documents/testpy/test.py", line 1, in <module>
    from .hello import hhh
ImportError: attempted relative import with no known parent package

python3 test2.py  可以单独运行
hello.py
hhhh
test2.py

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注