装饰器扩展类功能

对类中属性访问,并修改他的行为

  可以直接使用类装饰器

"""
类装饰器扩展
类功能
"""


def log_getattribute(cls):
    old_getattribute = cls.__getattribute__

    def new_getattribute(self, name):
        print("getting", name)
        return old_getattribute(self, name)

    cls.__getattribute__ = new_getattribute
    return cls


@log_getattribute
class Valley:
    def __init__(self):
        self.name: str = "xiao_gu_a"


print(Valley().name)

除此之外,使用继承,对__getattribute__进行重写也能实现,只不过要依赖于super,对技能要求会稍微高一点;

相比较而言,类装饰器更直观一点,而且不会引入新的继承体系,运行速度也会更快

 

posted on 2023-05-15 17:06  默玖  阅读(29)  评论(0编辑  收藏  举报

导航