Do you mean something like this? If so, you should define a __iter__ method that gives key-value pairs:
In [1]: class A(object): ...: def __init__(self): ...: self.pairs = ((1,2),(2,3)) ...: def __iter__(self): ...: return iter(self.pairs) ...: In [2]: a = A() In [3]: dict(a) Out[3]: {1: 2, 2: 3}
It also seems like dict trying to call .keys / __getitem__ before __iter__ , so you can do list(instance) and dict(instance) to return something completely different.
In [4]: class B(object): ...: def __init__(self): ...: self.d = {'key':'value'} ...: self.l = [1,2,3,4] ...: def keys(self): ...: return self.d.keys() ...: def __getitem__(self, item): ...: return self.d[item] ...: def __iter__(self): ...: return iter(self.l) ...: In [5]: b = B() In [6]: list(b) Out[6]: [1, 2, 3, 4] In [7]: dict(b) Out[7]: {'key': 'value'}
source share