वहाँ एक अंतर है, दोनों जब वहाँ एक bar
मॉड्यूल या foo
पैकेज के अंदर पैकेज है के लिए है, और अगर bar
सभी पर एक मॉड्यूल नहीं है।
माना जाता है निम्नलिखित foo
पैकेज: __init__.py
फ़ाइल एक वैश्विक नाम bar
भी को परिभाषित करता है
foo/
__init__.py
bar.py
है, तो पहला उदाहरण कि वस्तु आयात करेगा। दूसरा उदाहरण bar.py
मॉड्यूल आयात करेगा।
हालांकि, एक बार foo.bar
मॉड्यूल आयात किया गया है, पायथन आयात मशीनरी नाम bar
foo
पैकेज में सेट हो जाएगा, __init__.py
में पहले से मौजूद किसी bar
वैश्विक जगह:
$ ls -1 foo/
__init__.py
bar.py
$ cat foo/__init__.py
bar = 'from the foo package'
$ cat foo/bar.py
baz = 'from the foo.bar module'
$ python
Python 2.7.12 (default, Aug 3 2016, 18:12:10)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo import bar
>>> bar
'from the foo package'
>>> import foo.bar as bar
>>> bar
<module 'foo.bar' from 'foo/bar.pyc'>
>>> bar.baz
'from the foo.bar module'
>>> from foo import bar
>>> bar
<module 'foo.bar' from 'foo/bar.pyc'>
अन्य मामले में जहां है नहींbar.py
सबमिशन है। foo
या तो एक पैकेज, या एक साधारण मॉड्यूल हो सकता है। उस मामले में from foo import bar
हमेशा foo
मॉड्यूल में एक वस्तु के लिए दिखाई देगा, और import foo.bar as bar
हमेशा असफल हो जायेगी:
$ cat foo.py
bar = 'from the foo module'
$ python
Python 2.7.12 (default, Aug 3 2016, 18:12:10)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.bar
'from the foo module'
>>> from foo import bar
>>> bar
'from the foo module'
>>> import foo.bar as bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named bar
ध्यान दें कि सभी मामलों में जहां आयात सफल होता है, तो आप एक वैश्विक नाम bar
कुछ करने के लिए बाध्य के साथ खत्म, या तो मॉड्यूल से एक ऑब्जेक्ट, या मॉड्यूल ऑब्जेक्ट।