Skip to main content
 首页 » 编程设计

python之如何指向变量的值

2025年05月04日16zhengyun_ustc

为了避免写十几次又长又丑的三进制,比如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 

谢谢!

请您参考如下方法:

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

gName   = getattr(root, "name", "No Name") 
err_tst = getattr(root, "not-there", "Error OK") 

第一个参数是对象,第二个是属性,第三个是可选的,是在属性不存在时返回的默认值(如果省略最后一部分,将返回一个 AttributeError 被提升)。

上面两行代码等价于:

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