繁体   English   中英

Python类修饰器将元素访问转换为属性访问

[英]Python class decorator converting element access to attribute access

我正在寻找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

这样的装饰器已经存在吗? 如果没有,实施它的正确方法是什么? 我应该在foo类上包装__new__并将__getitem____setitem__属性添加到实例吗? 那么如何使它们正确地绑定到新类上呢? 我知道DictMixin可以帮助我支持所有dict功能,但是我仍然必须以某种方式获取类中的基本方法。

装饰者需要添加__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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM