模块 xml.etree.ElementTree 和 xml 有什么关系? [英] How are the modules xml.etree.ElementTree and xml related?

查看:64
本文介绍了模块 xml.etree.ElementTree 和 xml 有什么关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是专业程序员,刚开始学习python.我只是想出来,因为我可以做到:

<预><代码>>>>从 xml.etree.ElementTree 导入元素>>>var = Element("某事")

并不意味着我可以:

<预><代码>>>>导入xml>>>var = xml.etree.ElementTree.Element("Something")

事实上,这样做:

<预><代码>>>>导入xml>>>目录(xml)['_MINIMUM_XMLPLUS_VERSION', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

etree 甚至没有作为 xml 提供的方法之一出现.xml 和 xml.etree.ElementTree 有什么关系?为什么我看不到etree作为xml的方法之一?

解决方案

xml.etreexml .它只会在您 import xml.etree 后出现在 xml 的命名空间中.父模块可以在初始化时导入其子模块(例如,在 2.7 中,os 导入 os.path1),但不需要这样做.

相反,当您直接从包中导入模块时,会先自动导入包.

奇怪的是,我在文档中找不到任何说明这一点的措辞.但测试表明,这正是发生的事情:

<小时>

$ cat test/__init__.py打印包初始化"导入回溯traceback.print_stack()$猫测试/module.py打印模块初始化"导入回溯traceback.print_stack()$蟒蛇<...>>>>导入 test.module包初始化文件<stdin>",第 1 行,位于 <module>文件test\__init__.py",第 3 行,在 <module> 中traceback.print_stack()模块初始化文件<stdin>",第 1 行,位于 <module>文件test\module.py",第 3 行,在 <module> 中traceback.print_stack()

<小时>

1虽然没有记录,所以不要依赖这个

I am not a professional programmer, and I'm just starting to study python. I just figured out that just because I could do:

>>> from xml.etree.ElementTree import Element
>>> var = Element("Something")

doesn't mean I can do:

>>> import xml
>>> var = xml.etree.ElementTree.Element("Something")

In fact, doing this:

>>> import xml
>>> dir(xml)
['_MINIMUM_XMLPLUS_VERSION', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

etree doesn't even appear as one of the methods provided by xml. What is the relation between xml and xml.etree.ElementTree? Why can I not see etree as one of xml's methods?

解决方案

xml.etree is a child module to xml package. It only shows up in xml's namespace after you import xml.etree. A parent may import its child modules on its initialization (e.g. in 2.7, os imports os.path1) but it's not required to do so.

Conversely, when you import a module from a package directly, the package is automatically imported first.

Strangely, I couldn't find any phrasing in the docs stating this. But a test shows that this is exactly what happens:


$ cat test/__init__.py

print "package init"
import traceback
traceback.print_stack()

$ cat test/module.py

print "module init"
import traceback
traceback.print_stack()

$ python
<...>
>>> import test.module
package init
  File "<stdin>", line 1, in <module>
  File "test\__init__.py", line 3, in <module>
    traceback.print_stack()
module init
  File "<stdin>", line 1, in <module>
  File "test\module.py", line 3, in <module>
    traceback.print_stack()


1this is not documented though so don't rely on this

这篇关于模块 xml.etree.ElementTree 和 xml 有什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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