基本上我做的是:
attrs = dir(oe)
for attr in attrs:
attr_obj = getattr(oe, attr)
.... more code ...
但是 getattr
调用失败并显示:AttributeError: no such child: comment
oe
是 lxml.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() 时可能不准确。
关于python - dir(element) 返回不存在的元素。尝试使用 getattr(element, ...) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363681/