问题
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 = foo()
print myfoo.x # gives 1
print myfoo['y'] # gives 2
myfoo['z'] = 3
print myfoo.z # gives 3
Does such decorator exist somewhere already? If not, what is the proper way to implement it? Should I wrap __new__
on class foo
and add __getitem__
and __setitem__
properties to the instance? How make these properly bound to the new class then? I understand that DictMixin
can help me support all dict
capabilities, but I still have to get the basic methods in the classes somehow.
回答1:
The decorator needs to add a __getitem__ method and a __setitem__ method:
def DictAccess(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:
class bar:
pass
@DictAccess
class foo(bar):
x = 1
y = 2
myfoo = foo()
print myfoo.x # gives 1
print myfoo['y'] # gives 2
myfoo['z'] = 3
print myfoo.z # gives 3
That test code produces the expected values:
1
2
3
来源:https://stackoverflow.com/questions/9106076/python-class-decorator-converting-element-access-to-attribute-access