You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数中如何传入属性选择参数而非字符串值?

解决方法

你的问题核心是通过字符串形式的属性名获取对象的实际属性值,原来的写法把属性路径拼成了字符串,而vars()/locals()这类方法只能访问变量名,不能直接解析对象的属性链。

直接用Python内置的getattr()函数就能解决,它专门用来通过字符串获取对象的属性:

def get_list(api, val=None):
    response = []
    for item in api:
        if val is not None:
            # 通过getattr获取item的val属性值
            response.append(getattr(item, val))
        else:
            # 如果没传属性名,直接返回整个对象
            response.append(item)
    return response

# 调用示例
devices = get_list(api.devices.all(), 'name')
print(devices)

补充说明

  • getattr(obj, attr_name)会直接返回obj.attr_name的实际值,完美匹配你的需求
  • 如果需要处理嵌套属性(比如item.device.name),可以自己写个递归解析的小函数:
def get_nested_attr(obj, attr_path):
    attrs = attr_path.split('.')
    for attr in attrs:
        obj = getattr(obj, attr)
    return obj

# 调用时可以传嵌套路径
devices = get_list(api.devices.all(), 'device.name')

内容的提问来源于stack exchange,提问作者Skylark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:05:24