簡體   English   中英

在類的__iter__方法中產生字典鍵,值對

[英]Yielding a dictionary key, value pair in __iter__ method of a class

我有一堂超級簡單的課:

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

我使用如下:

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

我想遍歷alex ,以便我返回attributes_to_values屬性中的鍵和相應的值。

我嘗試插入以下內容:

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

但這不起作用...

for a, v in alex:
    print(a, v)

追溯(最近一次呼叫最近):文件“”,ValueError中的第1行:太多值無法解包(預期2)

如果您有一個類似item()的可迭代對象yield from則可以從中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)

版畫

name Alex
age 30
happiness 100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM