3

基本上我所做的是:

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

  .... more code ...

getattr通话失败:AttributeError: no such child: comment

oe是图书馆ObjectifiedElement的一个。lxml.objectify

当我查看oePyCharm 时,它显示了该comment属性,但也无法解决它。

这里发生了什么?dir当它不存在时如何显示该属性?

4

1 回答 1

3

我不是专家,但 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([object]) 不带参数,返回当前本地范围内的名称列表。使用参数,尝试返回该对象的有效属性列表。

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

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

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

于 2015-10-27T09:37:42.660 回答