Python class decorator converting element access to attribute access

↘锁芯ラ 提交于 2019-12-11 07:45:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!