dir(元素) 返回不存在的元素.尝试使用 getattr(element, ..) 失败



基本上我所做的是:

attrs = dir(oe)
for attr in attrs:
  attr_obj = getattr(oe, attr)
  .... more code ...

getattr调用失败,并显示:AttributeError: no such child: comment

oelxml.objectify图书馆的ObjectifiedElement

当我使用 PyCharm 查看oe时,它显示了 comment 属性,但也无法解决它。

这是怎么回事?当此属性不存在时,如何通过dir显示此属性?

我不是专家,但 lxml 可能会重新定义__getattr__ .从他们的源代码:

def __getattr__(self, tag):
    u"""Return the (first) child with the given tag name.  If no namespace
    is provided, the child will be looked up in the same one as self.
    """
    if is_special_method(tag):
        return object.__getattr__(self, tag)
    return _lookupChildOrRaise(self, tag)

见 https://github.com/lxml/lxml/blob/master/src/lxml/lxml.objectify.pyx

此外,关于dir方法,您有:

目录([对象](如果没有参数,则返回当前本地范围内的名称列表。使用参数,尝试返回该对象的有效属性列表。

如果对象具有名为 dir(( 的方法,则将调用此方法,并且必须返回属性列表。这允许实现自定义 getattr(( 或 getattribute(( 函数的对象自定义 dir(( 报告其属性的方式。

如果对象

不提供 dir((,则该函数会尽力从对象的 dict 属性(如果已定义(及其类型对象中收集信息。生成的列表不一定完整,当对象具有自定义 getattr(( 时可能不准确。

请参阅 https://docs.python.org/2/library/functions.html#dir

最新更新