Specificity in importing python module?

天大地大妈咪最大 提交于 2019-12-13 01:28:01

问题


I've been working with the PySerial library for pythonPyserial API, and I can't seem to understand why I have to specifically import a certain part of the module.

This will give me an error:

import serial
for item in serial.tools.list_ports.comports():
    print item

The above snippet will return "AttributeError: type object 'Serial' has no attribute 'tools'"

If I import that attribute specifically, I get no errors:

import serial.tools.list_ports
for item in serial.tools.list_ports.comports():
    print item

Can someone help me understand why the first import won't run the comports() method?

I understand that importing fewer items into memory is a best practice, but I'm also using other methods from the PySerial module. It seems redundant to import both serial and serial.tools.list_ports.


回答1:


Importing serial will result in the creation of all names that the module creates. This sounds self-obvious until you realize that serial does not create any attribute called "tools" within it. This is in fact a separate module.

import does you the favor of importing parent modules, which is why importing serial.tools.list_ports also imports serial.tools. It does also import serial, but you should import it explicitly rather than having Python do it for you by accident.

>>> import this
The Zen of Python, by Tim Peters

 ...
Explicit is better than implicit.
 ...


来源:https://stackoverflow.com/questions/25274499/specificity-in-importing-python-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!