Python类修饰器将元素访问转换为属性访问 [英] Python class decorator converting element access to attribute access

查看:71
本文介绍了Python类修饰器将元素访问转换为属性访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Python类的装饰器,该装饰器会将任何元素访问转换为属性访问,如下所示:

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

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

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.

推荐答案

装饰器需要添加 __ getitem __ 方法和 __ setitem __ 方法:

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

这篇关于Python类修饰器将元素访问转换为属性访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆