python – 如何修改类__dict__(mappingproxy)?

参见英文答案 > How to assign a new class attribute via __dict__?                                    1个
我想将装饰器应用于类中的每个方法.我没有类的源代码,所以我不能直接应用装饰器.我想调用一些接受类的函数并添加装饰器.

但问题是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

解决方法:

使用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'
上一篇:Java,Base64:如何使用Decorator Pattern编写Base64OutputStream类


下一篇:Python – 我可以以编程方式从类实例中修饰类方法吗?