[英]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: 我正在寻找Python类的装饰器,该装饰器会将任何元素访问都转换为属性访问,如下所示:
@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? 我应该在foo
类上包装__new__
并将__getitem__
和__setitem__
属性添加到实例吗? 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. 我知道DictMixin
可以帮助我支持所有dict
功能,但是我仍然必须以某种方式获取类中的基本方法。
The decorator needs to add a __getitem__ method and a __setitem__ method: 装饰者需要添加__getitem__方法和__setitem__方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.