In this post:
I was playing around with blurring the distinction between getters and setters in Python objects. tarcisiocrocomo gave me this tip for the win:
I was able to get the same results with this:
__getitem__ = object.__getattribute__
__setitem__ = object.__setattr__
Are there any meaningful differences?
Victory! So here’s the little Ob class I wrote and I throw it around where I want attributes and items… usually in unit tests, although when I’m good I use flexmock.
class Ob(object): __getitem__ = object.__getattribute__ __setitem__ = object.__setattr__ def __init__(self, **kwargs): # see if the passed in initialization values if kwargs: for key in kwargs.keys(): self[key] = kwargs[key]
Now I just need to get it to pretty print… hm….
from pprint import pprint ob = Ob() ob.name = 'hello!' pprint(ob) ....hrm