Skip to content Skip to sidebar Skip to footer

Python Class Decorator Converting Element Access To Attribute Access

I'm looking for a decorator for Python class that would convert any element access to attribute access, something like this: @DictAccess class foo(bar): x = 1 y = 2 myfoo

Solution 1:

The decorator needs to add a __getitem__ method and a __setitem__ method:

defDictAccess(kls):
    kls.__getitem__ = lambda self, attr: getattr(self, attr)
    kls.__setitem__ = lambda self, attr, value: setattr(self, attr, value)
    return kls

That will work fine with your example code:

classbar:
    pass@DictAccessclassfoo(bar):
    x = 1
    y = 2

myfoo = foo()
print myfoo.x # gives 1print myfoo['y'] # gives 2
myfoo['z'] = 3print myfoo.z # gives 3

That test code produces the expected values:

1
2
3

Post a Comment for "Python Class Decorator Converting Element Access To Attribute Access"