美文网首页
python 用装饰器重写类的方法

python 用装饰器重写类的方法

作者: SkTj | 来源:发表于2019-12-04 11:06 被阅读0次

    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
    

    Example use

    @log_getattribute
    class A:
    def init(self,x):
    self.x = x
    def spam(self):
    pass

    diaoyong

    a = A(42)
    a.x
    getting: x
    42
    a.spam()
    getting: spam

    相关文章

      网友评论

          本文标题:python 用装饰器重写类的方法

          本文链接:https://www.haomeiwen.com/subject/azrbvctx.html