导入python模块的特殊性? [英] Specificity in importing python module?

查看:185
本文介绍了导入python模块的特殊性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用PySerial库进行python Pyserial API ,我可以'我似乎明白为什么我必须专门导入模块的某个部分。

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.

这会给我一个错误:

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

上面的代码片段将返回AttributeError:type object'Serial'没有属性'tools'

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

有人可以帮助我理解为什么第一次导入不会运行comports()方法?

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

我知道将较少的项目导入内存是最佳做法,但我也使用PySerial模块中的其他方法。导入serial和.tools.list_ports似乎是多余的。

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.

推荐答案

导入 serial 将导致创建模块创建的所有名称。在你意识到 serial 没有在其中创建任何称为工具的属性之前,这听起来是不言而喻的。这实际上是一个单独的模块。

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 您是否支持导入父模块,这就是导入的原因 serial.tools.list_ports 还导入 serial.tools 。它导入 serial ,但你应该明确地导入它,而不是让Python偶然为你做。

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.
 ...

这篇关于导入python模块的特殊性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆