使用装饰器修改类定义

修改类定义可以通过单继承,多继承(mixin),以及元类等。其实,装饰器也可以修改类定义,并且和上述提到的方案相比,更简洁直观,性能也更强。
如下:

def log_getattribute(cls):
    # Get the original implementation
    orig_getattribute = cls.__getattribute__

    # Make a new definition
    def new_getattribute(self, name):
        print('getting', name)
        return orig_getattribute(self, name)

    # Attach to the class and return
    cls.__getattribute__ = new_getattribute
    return cls


@log_getattribute
class A:
    def __init__(self, x):
        self.x = x

    def spam(self):
        pass


>>> a = A(42)
>>> print(a.x)
getting x
42
>>> a.spam()
getting spam
posted @ 2020-02-04 21:35  Jeffrey_Yang  阅读(211)  评论(0编辑  收藏  举报