如何指向变量的值

Dei*_*ill 1 python variables

为了避免写一个长而丑陋的三元十几次,比如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)
Run Code Online (Sandbox Code Playgroud)

实际上,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

谢谢!

iCo*_*dez 6

GetThis不需要您的功能,因为您可以简单地使用getattr:

gName   = getattr(root, "name", "No Name")
err_tst = getattr(root, "not-there", "Error OK")
Run Code Online (Sandbox Code Playgroud)

第一个参数是对象,第二个参数是属性,第三个参数是可选的,如果属性不存在则返回默认值(如果省略最后一个部分,AttributeError则引发一个).

上面两行代码相当于:

gName   = root.name if hasattr(root, "name") else "No Name"
err_tst = root.not-there if hasattr(root, "not-there") else "Error OK"
Run Code Online (Sandbox Code Playgroud)