Py学习  »  Python

是否可以在预定义的可变数据上创建python迭代器?

Wilduck • 6 年前 • 1845 次点击  

我可能做错了,如果是的话,请告诉我,但我很好奇是否可能发生以下情况:

我有一个类,它包含许多字典,每一个字典都将名称对到一个给定类的不同对象集。例如:

items = {"ball" : ItemInstance1, "sword" : ItemInstance2}
people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3}

然后,我的类将保存当前项目和可用人员,这些项目和人员将随着状态的更改而更改:

Class State:
    def __init__(self, items, people):
        self.items = items
        self.people = people

我想定义一个 伊特尔 ()和next()方法,使其迭代其属性中的所有值。我的第一个问题是这是否可能。如果是,它是否能够支持以下情况:

我定义项目和人员如下:

state = State(items, people)
for names, thing in state:
    print name + " is " + thing.color

items[cheese] = ItemInstance3
for names, thing in state:
    print name + " weighs " + thing.weight

虽然我觉得这在我的代码中是有用的,但我不知道这是可能的还是正确的方法。关于用户定义的迭代器,我所读到的所有内容都建议它们的每个实例只能使用一次。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30330
 
1845 次点击  
文章 [ 2 ]  |  最新文章 6 年前