Is it possible to add dict functionality to user created classes?
ie:
class Foo(object):
def __init__(self, x, y):
self.x
self.y
def __dict__(self):
return {'x': self.x, 'y': self.y}
f = Foo()
dict(f) <-- throws TypeError: iteration over non-sequence
The
dictconstructor expects either a mapping or an iterable of key/value pairs as a parameter, so your class needs to either implement the mapping protocol or be iterable.Here’s an example how to got about the latter approach:
Example usage:
I don’t know how useful this is, though. You could just do
which would work without implementing
__iter__()on your class.