In a defined object some values are kept in a dict, and I want to iterate over the contents in that dict as when referring to a plain dict, thus with directly access using [], and loop using e.g. .items(). Code structure is:
class Klass: def __init__(self, values): self.values = values self.more = None def __getitem__(self, name): return self.values[name] def __iter__(self): pass # TBD[How to make this ?] d = {'alfa': 1, 'bravo': 2, 'charlie': 3} k = Klass(d) for key in k: print(key) # Expected to print keys from self.values for (key, value) in k.items(): print(key, value) # Expected to print key and value from self.values for key in k.keys(): print(key) # Expected to print key from self.values for value in k.values(): print(value) # Expected to print value from self.values How to write the __iter__ and, other required methods, so this kind of access is possible through an instance of Klass?
for item in self.values: yield item?.valuesshould be avoided..Torxedwas proposing a implementation for__iter__, making it a generator function. Not needed here, not withiter(), however.