【问题标题】:Iterate through a dictionary attribute of a class [duplicate]遍历类的字典属性[重复]
【发布时间】:2021-05-25 07:37:02
【问题描述】:

任何人都可以为这个简约示例提供适当的解决方案吗?我想遍历类的字典字段:

class MyClass:

    _a_dic : dict

    def __init__(self, a_dic : dict = None):
        if a_dic:
            self._a_dic = a_dic
        else:
            self._a_dic = {}

    @property
    def a_dic( self ):
        return self._a_dic

    def __iter__(self):
        ???

    def __next__(self):
        ???

bruh = MyClass( {'one' : 1, 'two' : 2} )

print( [ t for t in bruh ] )
> ['one', 'two']

print( [ bruh[t] for t in bruh ] )
> [1, 2]

我还想了解如果我使用列表而不是字典,这将如何工作。

【问题讨论】:

    标签: python python-3.x iterator


    【解决方案1】:

    只需实现__iter__ 以委托给该字典,

    class MyClass:
    
        _a_dic : dict
    
        def __init__(self, a_dic : dict = None):
            if a_dic:
                self._a_dic = a_dic
            else:
                self._a_dic = {}
        
        def __iter__(self):
            return iter(self._a_dic)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2021-08-07
      • 1970-01-01
      • 2014-10-26
      • 2012-10-29
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多