Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

python - difference between from x import y and import x.y

So I am confused as what the difference is...Here is some code to display my confusion:

>>> import collections.OrderedDict as od
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named OrderedDict
>>> from collections import OrderedDict as od
>>> od
<class 'collections.OrderedDict'>

explanation:

import collections.OrderedDict did not find the module, yet from collections import OrderedDict found it?! What is the difference between those two statements?

the class is read as collections.OrderedDict, so I don't understand why the first attempt was unable to find the module

note:

I am simply using collections as an example. I am not looking for specifically why my example acted the way it did for collections, but rather an explanation for what the different lines of code are actually requesting as far as imports go. If you would like to include an explanation on the error, feel free! Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OrderedDict is a class within the collections module. When you see things like x.y and something is being imported from it, that means that "y" in this case is actually a module.

You should read the docs about how import works: here. It's long and involved but at the same time fairly straight forward in how it looks into the different packages and modules to find what should be brought into play. Specifically, the import statement itself and import system.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...