0

I have a container object like this:

class myclass():
    self.data = dict()
    self.otherattribute = 0 ## anything

how to write __iter__ and __next__ to implement:

for i in myclass:

equal to:

for i in myclass.data:
Bach
  • 6,145
  • 7
  • 36
  • 61
MacSanhe
  • 2,212
  • 6
  • 24
  • 32
  • You'll find that all your `myclass` instances seem to share the same `data` dict. Here's why and how to fix it: http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances – user2357112 May 29 '14 at 02:16

1 Answers1

2

You can just have __iter__ return an iterator:

class myclass(object):
    def __init__:
        self.data = {}

    def __iter__(self):
        return iter(self.data)

With that, I can do this:

c = myclass()
c.data['key1'] = 'val1'
c.data['key2'] = 'val2'

for k in c:
    print k

Which gets me:

key2
key1
larsks
  • 277,717
  • 41
  • 399
  • 399