在类的 __iter__ 方法中生成字典键、值对

ale*_*wis 2 python dictionary iterator class

我有一个超级简单的课程:

class Person():
    def __init__(self, attributes_to_values):
        self.attributes_to_values =  attributes_to_values
Run Code Online (Sandbox Code Playgroud)

我使用如下:

attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)
Run Code Online (Sandbox Code Playgroud)

我想进行迭代,alex以便返回attributes_to_values属性中的键和相应的值。

我尝试插入以下内容:

def __iter__(self):
    yield list(self.attributes_to_values.items())
Run Code Online (Sandbox Code Playgroud)

但这不起作用...

for a, v in alex:
    print(a, v)
Run Code Online (Sandbox Code Playgroud)

回溯(最近一次调用):ValueError 中的文件“”,第 1 行:太多值无法解压(预期为 2)

Mar*_*yer 5

如果你有一个像你这样的可迭代对象,item()你可以yield from

class Person():
    def __init__(self, attributes_to_values):
        self.attributes_to_values =  attributes_to_values

    def __iter__(self):
        yield from self.attributes_to_values.items()


attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)

for a, v in alex:
    print(a, v)
Run Code Online (Sandbox Code Playgroud)

印刷

name Alex
age 30
happiness 100
Run Code Online (Sandbox Code Playgroud)