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

Python如何通过存储属性名的数组调用类实例对象的对应属性

解决方案

方法1:直接使用Python内置getattr()函数(无需修改原有类定义)

getattr()是Python原生的内置函数,专门用于通过字符串格式的属性名读取对象属性值,是实现该需求最简便的方案:

# 原有代码无需调整
class my_data:
    def __init__(self,a,b,c,d):
        self.a = 'e'
        self.b = 'f'
        self.c = 'g'
        self.d = 'h'

test=my_data('a','b','c','d')
index=['a','b','c','d']

# 实现需求的正确写法
my_var = getattr(test, index[2])
print(my_var) # 输出结果为g

循环场景下的使用示例:

# 遍历index列表批量读取所有对应属性值
for attr_name in index:
    print(getattr(test, attr_name))
# 依次输出 e f g h

方法2:为类添加__getitem__魔法方法,支持字典式取值

如果业务中需要频繁通过字符串属性名取值,可以修改类定义添加魔法方法,后续调用语法更简洁:

class my_data:
    def __init__(self,a,b,c,d):
        self.a = 'e'
        self.b = 'f'
        self.c = 'g'
        self.d = 'h'
    # 新增__getitem__魔法方法
    def __getitem__(self, key):
        return getattr(self, key)

test=my_data('a','b','c','d')
index=['a','b','c','d']

# 直接用类似字典的语法取值
my_var = test[index[2]]
print(my_var) # 输出结果为g

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:24:03