【问题标题】:How to modify class __dict__ (a mappingproxy)? [duplicate]如何修改类 __dict__ (映射代理)? [复制]
【发布时间】:2013-11-29 22:10:06
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x decorator


    【解决方案1】:

    使用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'
    

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 2019-11-23
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多