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

Python自定义类迭代器无法遍历默认类属性该如何解决?

问题原因

未被实例显式覆盖的类属性不会出现在实例的__dict__中,默认存储在类本身的__dict__里,你之前的实现仅遍历实例的__dict__,自然拿不到未赋值的默认类属性。你后续修改的版本还是仅遍历实例的__dict__,所以依然无法读取到默认类属性。

解决方法

修改__iter__方法,同时遍历类层面的属性和实例层面的属性,自动跳过私有属性、类方法,同时处理实例覆盖类属性的场景,还能兼容实例后续新增的自定义属性:

class MyClass:
    def __iter__(self):
        seen_attrs = set()
        # 先遍历类定义的属性,自动获取实例覆盖后的值
        for attr_name in type(self).__dict__:
            # 跳过魔法方法、私有属性
            if attr_name.startswith("__"):
                continue
            attr_val = getattr(self, attr_name)
            # 跳过类方法、实例方法等可调用对象
            if callable(attr_val):
                continue
            seen_attrs.add(attr_name)
            yield attr_val
        # 再遍历实例新增的、类中没有定义的属性
        for attr_name in self.__dict__:
            if attr_name in seen_attrs or attr_name.startswith("__"):
                continue
            attr_val = getattr(self, attr_name)
            if callable(attr_val):
                continue
            yield attr_val

    first_var: str = "asdf"
    second_var: str = "tasdt"

效果验证

  • 实例化后直接遍历,就能正常输出默认值asdf、tasdt
  • 显式给实例属性赋值后遍历,会输出修改后的值hello、world
  • 给实例新增类中未定义的属性,也会被正常遍历到

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:51:02