python基础 25 专题 装饰器

90 阅读1分钟

一 Decorator:装饰器

 1. 装饰器的需求:AOP的思想 
     AOP:面向切面的编程 
     切面:向代码段中切入另一段代码,不修改原有的代码 
     用于:1.插入日志 2. 性能测试 3. 事务处理 
     装饰器的使用:切入一段代码,不去影响业务---辅助功能 
 2. 可以给代码或对象添加额外功能 
     辅助性质功能 
 3. 语法: 关键字:@ 
     1. 装饰器必须出现在要修饰对象的前一行 
     2. 装饰器可以是函数,可以是类 
     3. 将被修饰的对象作为参数传递给装饰器,再次对装饰器返回的对象进行圆括号调用 
     

二 基本形式

# def A(x): # 装饰器函数 
    # print('A') 
    # return x 
    
# @A 
# def B(): 
    # print('B') 
# 
# B() 

# 利用函数的嵌套 
# def funA(x): 
    # def funB(): 
        # print('inner functionB') 
    # funB() 
    # return x 
    
# # @funA 
# def funC(): 
    # print('C') 
# 
# funC() 

# 利用闭包 
# def funA(x): 
    # def funB(): 
        # print('inner functionB')  
        # return x() #
    # return funB 
# 
# @funA 
# def funC(): 
    # print('C') 
# 
# funC() 

# 用类实现

# class A: 
    # def __init__(self,x): 
        # self.x=x 
        
    # def __call__(self): 
        # print('B') 
        # self.x()
        # return None 
# 
# 
@A # A(C)()
# def C(): 
    # print('C') 
# 
# C() 

# 高级形式 
def A(x,y): 
    print(x,y) 
    def B(z): 
        print('B') 
        return z 
    return B 
    
@A(1,2) # A(1,2)(C)() 
def C(): 
    print('C') 

C()

三 Python中内置的装饰器

1. @staticmethod 
2. @classmethod 
3. @property #


@staticmethod 
class Student: 
    def learn1(self): 
        print('this is learn1') 

    @staticmethod 
    def learn2(): 
        print('this is learn2') 
s=Student() 
s.learn2() 

# @classmethod 
class Student: 
    def learn1(self): 
        print('this is learn1',self) 
        
    @staticmethod 
    def learn2(): 
        print('this is learn2')
        
    @classmethod 
    def learn3(cls): 
        print('this is learn3',cls) 
        
s=Student() 
s.learn1() 
s.learn3() 


# @property 
class Student: 
    def __init__(self): 
        self.__score=100 
        
    @property 
    def hehe(self): 
        return self.__score 
        
    @hehe.getter
    def hehe(self): 
        return self.__score 
        
    @hehe.setter 
    def hehe(self,newScore): 
        self.__score=newScore 
    
    @hehe.deleter 
    def hehe(self): 
        del self.__score 
    
s=Student() 
print(s.hehe) 
s.hehe=200 
print(s.hehe)