Python 装饰器修饰类

一、修饰类方法

def load_detail(func):
    def call_func(self, secu):
        if not self._detail:
            secus = open_securities_detail_pk(secu=secu)
            for i in secus:
                self._detail[i] = Security(**securities[i])
       
        return func(self)
    return call_func


class SecuStore(object):

    def __init__(self):
        
        self._detail = {}

    @load_detail
    def get_all_indexs(self):
        return self._detail

SecuStore().get_all_indexs(_type)


def catch_exception(origin_func):
    def wrapper(self, *args, **kwargs):
        try:
            u = origin_func(self, *args, **kwargs)
            return u
        except Exception:
            self.revive() #不用顾虑,直接调用原来的类的方法
            return 'an Exception raised.'
    return wrapper


class Test(object):
    def __init__(self):
        pass

    def revive(self):
        print('revive from exception.')
        # do something to restore

    @catch_exception
    def read_value(self):
        print('here I will do something.')

二 、修饰类本身 

def decorator(aClass):
    class newClass:
        def __init__(self, age):
            self.total_display   = 0
            self.wrapped         = aClass(age)
        def display(self):
            self.total_display += 1
            print("total display", self.total_display)
            self.wrapped.display()
    return newClass

@decorator
class Bird:
    def __init__(self, age):
        self.age = age
    def display(self):
        print("My age is",self.age)

eagleLord = Bird(5)
for i in range(3):
    eagleLord.display()
回答: 在Python中,装饰器可以用来修饰装饰器可以在不修改原始代码的情况下,为添加额外的功能。通常,装饰器是通过在定义之前使用@符号来应用的。装饰器可以在定义之前对进行修饰,从而为添加新的功能。例如,可以定义一个装饰器函数,然后使用@符号将其应用于定义之前。装饰器函数可以在返回之前对进行修改,从而为添加新的方法或属性。\[2\]通过装饰器修饰在实例化时会自动调用装饰器函数,并在返回之前对进行修改。这样,原始就被装饰器修饰后,具有了额外的功能。\[2\] #### 引用[.reference_title] - *1* [python装饰器详解](https://blog.youkuaiyun.com/weixin_44992737/article/details/125868592)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python 使用装饰器装饰](https://blog.youkuaiyun.com/weixin_30721899/article/details/96861904)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值