如果我做错了,请告诉我,但我很好奇以下是否可能:
我有一个类,其中包含许多字典,每个字典将名称与给定类的不同对象集合配对。例如:
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
我希望定义一个iter()和next()方法,使其能够遍历其属性中的所有值。我的第一个问题是这是否可行。如果是,它是否能支持以下情况:
我以上述方式定义了items和people:
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
虽然我觉得这在我的代码中会很有用,但我不知道它是否可行或是否是正确的方法。关于用户定义迭代器,我读到的所有内容都表明它们的每个实例只能使用一次。