如何修改类__dict__(mappingproxy)?

时间:2013-11-16 14:01:20

标签: python python-3.x decorator

我想将装饰器应用于类中的每个方法。我没有类的源代码,所以我不能直接应用装饰器。我想调用一些接受类的函数并添加装饰器。

但问题是testclass.__dict__mappingproxy对象,它至少不支持任何赋值或修改。所以问题是如何避免这种刺激性限制并应用装饰器?

以下是尝试失败的代码:

class qwer:
    def test(self):
        print('test')

def decor(func):
    def w(*args, **named_args):
        print('decor')
        func(*args, **named_args)
    return w

qwer.__dict__['test'] = decor(qwer.__dict__['test'])

错误:

TypeError: 'mappingproxy' object does not support item assignment

1 个答案:

答案 0 :(得分:7)

使用setattr在类上设置属性:

>>> setattr(qwer, 'test', decor(qwer.__dict__['test']))
>>> qwer.test
<function decor.<locals>.w at 0xb5f10e3c>

<强>演示:

>>> class A:                 
    pass
... 
>>> A.__dict__['foo'] = 'bar'
Traceback (most recent call last):
  File "<ipython-input-117-92c06357349d>", line 1, in <module>
    A.__dict__['foo'] = 'bar'
TypeError: 'mappingproxy' object does not support item assignment

>>> setattr(A, 'foo', 'bar')
>>> A.foo
'bar'