Python 遍历类的dictionary属性
有人能为这个极简主义的例子提供一个合适的解决方案吗?我想遍历类的dictionary字段:Python 遍历类的dictionary属性,python,python-3.x,iterator,Python,Python 3.x,Iterator,有人能为这个极简主义的例子提供一个合适的解决方案吗?我想遍历类的dictionary字段: 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( s
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]
我还想了解如果我使用列表而不是字典,这将如何工作。只需实现
\uuuuu iter\uuuuuu
就可以委托给该指令
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)