Python类装饰器转换元素访问属性访问权限

时间:2012-02-02 01:55:01

标签: python decorator

我正在寻找一个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功能,但我仍然必须以某种方式获得类中的基本方法。

1 个答案:

答案 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