How To Modify Class __dict__ (a Mappingproxy)?
I want to apply a decorator to every method in a class. I don't have source code of the class, so I can't directly apply the decorator. I want to call some function that accepts th
Solution 1:
Use setattr
to set an attribute on a class:
>>>setattr(qwer, 'test', decor(qwer.__dict__['test']))>>>qwer.test
<function decor.<locals>.w at 0xb5f10e3c>
Demo:
>>> classA:
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'
Post a Comment for "How To Modify Class __dict__ (a Mappingproxy)?"