zoukankan      html  css  js  c++  java
  • Python 装饰器---装饰类的两种方法

    这是在类的静态方法上进行装饰,当然跟普通装饰函数的装饰器区别倒是不大

    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()
    
    
  • 相关阅读:
    iOS开发-消息初认识
    小程序开发相关网址
    201703-4 地铁修建
    CCF 201703-3 Markdown
    UVALive 4998 Simple Encryption
    CCF 201609-4 交通规划
    CCF 201609-3 炉石传说
    UVALive 4270 Discrete Square Roots
    CCF 201604-2 俄罗斯方块
    codeforces 710E Generate a String
  • 原文地址:https://www.cnblogs.com/wspblog/p/7646948.html
Copyright © 2011-2022 走看看