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

如何在Python类中通过字符串匹配同名实例属性并赋值?

动态设置实例属性的修复方案

你遇到的问题是因为在循环里写self.i时,Python会把i当成固定属性名去查找,而不是用变量i存储的字符串(比如'water'、'coffee')作为属性名,所以才会触发“不存在名为i的属性”的错误。

解决这个问题要用到Python内置的setattr()函数,它能动态给对象设置属性,用法如下:

for i in self.ingredients:
    setattr(self, i, ...)  # 将...替换为你要赋值的具体内容

举个完整示例,比如给咖啡机添加重置原料的方法:

class CoffeeMachine:
    def __init__(self):
        self.water = 400
        self.coffee = 45
        self.milk = 300
        self.ingredients = ['water', 'coffee', 'milk']
    
    def reset_to_initial(self):
        # 定义初始值映射
        initials = {'water': 400, 'coffee': 45, 'milk': 300}
        for ingredient in self.ingredients:
            # 动态设置对应属性的值
            setattr(self, ingredient, initials[ingredient])

如果需要动态获取属性值,对应的内置函数是getattr(),用法为getattr(self, ingredient),能返回该属性当前的取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:12:01