gpt4 book ai didi

python - 无法在 Python 3 中的 ElementTree.Element 实例上设置属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:36 24 4
gpt4 key购买 nike

我不明白为什么在 Python 3 中我不能向 ElementTree.Element 实例添加一些属性。这是区别:

在 Python 2 中:

Python 2.6.6 (r266:84292, Jun 18 2012, 14:18:47) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree import ElementTree as ET
>>> el = ET.Element('table')
>>> el.foo = 50
>>> el.foo
50
>>>

在 Python 3 中:

Python 3.3.0 (default, Sep 11 2013, 16:29:08) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree import ElementTree as ET
>>> el = ET.Element('table')
>>> el.foo = 50
>>> el.foo
AttributeError: foo
>>>

Python 2 由发行版 (CentOS) 提供。 Python 3 是从源代码编译的。

这是预期的行为、错误,还是我必须使用一些额外的标志重新编译 python 3?

更新:

一些说明:我试图在 Python 对象上设置属性,即在 Element 实例上。不是 XML 属性 (Element.attrib)。

这个问题实际上是在我尝试子类化 Element 时出现的。这是示例:

>>> class Table(ET.Element):
... def __init__(self):
... super().__init__('table')
... print('calling __init__')
... self.foo = 50
...
>>> t = Table()
calling __init__
>>> t.foo
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'foo'
>>>

这让我觉得 Element 类是以某种棘手的方式实例化的,但我无法弄清楚发生了什么。因此问题。

最佳答案

这可能是故意的...看看Can't set attributes of object class .如果当时他们没有增强 ElementTree 以使用槽而不是 dict,无论如何我都会感到惊讶。

不清楚您要做什么...您真的要设置 python 属性还是 XML 属性?如果是后者,你真的想这样做:

el = ET.Element('table')
el.set('foo', 50)
#or
el.attrib['foo'] = 50

如果你真的想添加 python 属性,你应该改为子类化,并且可能提供你自己的 Element/SubElement 函数来提供“包装”元素而不是标准元素。

2016 年 6 月 4 日更新:我的回答可能不清楚,但您可能需要执行以下操作(我通常使用 python 2.7):

class Table(ET.Element):
# Adding __slots__ gives it a known attribute to use
__slots__ = ('foo',)
def __init__(self):
super().__init__('table')
print('calling __init__')
self.foo = 50

关于python - 无法在 Python 3 中的 ElementTree.Element 实例上设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20995601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com