为了避免写一个长的,丑陋的三元十几次,例如p_count = root.pool_count if hasattr(root, 'pool_count') else (-1)
,我写了 GetThis(el,attr,err =“”)函数。
如何获得连接 el &的值的功能? attr 成为一个元素,而不是 attr 作为文字?
test_data = ("""
<rsp stat="ok">
<group id="34427465497@N01" iconserver="1" iconfarm="1" lang="" ispoolmoderated="0" is_member="0" is_moderator="0" is_admin="0">
<name>GNEverybody</name>
<members>245</members>
<pool_count>133</pool_count>
<topic_count>106</topic_count>
<restrictions photos_ok="1" videos_ok="1" images_ok="1" screens_ok="1" art_ok="1" safe_ok="1" moderate_ok="0" restricted_ok="0" has_geo="0" />
</group>
</rsp>
""")
################
from lxml import etree
from lxml import objectify
################
def GetThis(el, attr, err=""):
if hasattr(el, attr):
return el.attr
else:
return err
################
Grp = objectify.fromstring(test_data)
root = Grp.group
gName = GetThis(root, "name", "No Name")
err_tst = GetThis(root, "not-there", "Error OK")
p_count = root.pool_count if hasattr(root, 'pool_count') else (-1)
实际上,我收到以下错误:
Traceback (most recent call last):
File "C:/Mirc/Python/Temp Files/test_lxml.py", line 108, in <module>
gName = GetThis(root, "name", "")
File "C:/Mirc/Python/Temp Files/test_lxml.py", line 10, in GetThis
print (el.attr)
File "lxml.objectify.pyx", line 218, in lxml.objectify.ObjectifiedElement.__getattr__ (src\lxml\lxml.objectify.c:3506)
File "lxml.objectify.pyx", line 437, in lxml.objectify._lookupChildOrRaise (src\lxml\lxml.objectify.c:5756)
AttributeError: no such child: attr
谢谢!
答案 0 :(得分:6)
您不需要GetThis
功能,因为您只需使用getattr
:
gName = getattr(root, "name", "No Name")
err_tst = getattr(root, "not-there", "Error OK")
第一个参数是对象,第二个参数是属性,第三个参数是可选的,如果属性不存在则返回默认值(如果省略最后一个部分,则为{{1}而是提出了。)
上面两行代码相当于:
AttributeError
答案 1 :(得分:0)
Python有一个名为getattr(foo,“bar”)的函数,它返回foo对象的bar attr的值。只需阅读文档..