为什么python包中的_init__u; py.py中的命令行为不同于命令行?

2024-10-01 07:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

Python新手。 我正在尝试创建一个python包。文件结构为-

+-demo1
    +-nsdemo
        +- __init__.py
        +- bar.py

bar.py的内容是

bar_var = 'abc'

_init\u uuuupy.py的内容如下

print('this is nsdemo')
from nsdemo import bar

在sys.path中添加路径后,我尝试在导入nsdemo之后访问bar或bar_var,但出现以下错误:

>>> import nsdemo
this is nsdemo
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined

但当我从命令行执行相同操作时:

>>> import nsdemo
this is nsdemo
>>> from nsdemo import bar
>>> bar
<module 'nsdemo.bar' from 'demo1/nsdemo/bar.py'>
>>> bar.bar_var
'abc'

如果__init__.py中的代码应该在我导入包时运行,为什么它不会以与命令行相同的方式运行


Tags: 命令行frompyimport内容initisvar