我正在寻找一个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
这样的装饰器是否已存在于某个地方?如果没有,实施它的正确方法是什么?我应该将__new__
包裹在课程foo
上,并将__getitem__
和__setitem__
属性添加到实例中吗?如何使这些适当地绑定到新类呢?我知道DictMixin
可以帮助我支持所有dict
功能,但我仍然必须以某种方式获得类中的基本方法。
答案 0 :(得分:4)
装饰者需要添加 __ 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
这将适用于您的示例代码:
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
该测试代码产生预期值:
1
2
3