4
給出一個簡單的Python包與__init__.py
:爲什麼從模塊導入符號也會定義模塊符號?
$ ls -R foo/
foo/:
__init__.py bar.py
$ cat foo/bar.py
def do_stuff(): pass
$ cat foo/__init__.py
from .bar import *
我很驚訝,foo.bar
定義:
>>> import foo
>>> foo.bar
<module 'foo.bar' from 'foo/bar.pyc'>
我的from x import *
的理解是,它不會在當前範圍內定義x
。例如:
>>> from abc import *
>>> abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
爲什麼在我的第一個例子定義foo.bar
,即使我沒有import bar
裏面__init__.py
?