zoukankan      html  css  js  c++  java
  • python 装饰器实现

    简单装饰器实现:

    # -*- coding: utf-8 -*-
    '''
    装饰器的特点:对原函数是透明的
    
    
    实现方式是: 高阶函数+ 嵌套函数
    '''
    from _ctypes_test import func
    
    def decorator(func):
        '''
        定义装饰器 *args,**kwargs  这两个是为了接收不固定的参数
        '''
        def test(*args,**kwargs):
            print("test 装饰器运行------>")
            func(*args,**kwargs)
            print("test 装饰器运行结束")
            
        return test
    
    '''
    使用 @decorator 这种方式(@装饰器名字)来调用装饰器
    
    '''
    @decorator 
    def func_1():
        print("func_1方法被调用")
        
    @decorator
    def func_2(name):
        print("this is  func_2:",name)
        
    
    func_1()
    func_2("name")

    被装饰的函数带有返回值:

         
    '''
     被装饰的函数带返回值
    '''    
    
    def decorator_re(func):
        def  wrapper(*args,**kwargs):
            print("decorator is run ---->")
            res = func(*args,**kwargs)  #接收被装饰函数的返回值
            print("decorator stop ------")
            return res #返回
        return wrapper
            
            
    @decorator_re
    def func_re(name):
        print("my name is :",name)
        return name
    
    my_name = func_re("arturo")
    print(my_name)  
        
    return value

    根据type 选择指定装饰器:

    '''
    根据 type 运行指定的装饰器
    '''
    
    def decorator_name(decorator_type):
        def switch(func):
            def  wrapper(*args,**kwargs):
                if decorator_type=="name":
                        print("name decorator is run ---->")
                        res = func(*args,**kwargs)  #接收被装饰函数的返回值
                        print("name decorator stop ------")
                        return res #返回
                elif decorator_type=="fullName":
                        print("fullName decorator is run ---->")
                        res = func(*args,**kwargs)  #接收被装饰函数的返回值
                        print("fullName decorator stop ------")
                        return res #返回
            return wrapper
        return switch    
    @decorator_name(decorator_type="name")      
    def func_name(name):
        print("my name is :",name)
        return name
    
    @decorator_name(decorator_type="fullName")   
    def func_fullName(name):
        print("fullName is :",name)
        return name
    
    func_name("xiaoQang")
    func_fullName("wangwang")
    type
  • 相关阅读:
    程序人生,编程思想
    CentOS Linux Jenkins安装、部署、更新
    Git常用命令
    U盘安装Mac OS X要点
    Shell执行*.sql
    WebStorm远程调试Node.js
    svn常用命令
    敏捷开发相关编辑思想(SOA、DDD、REST、CQRS)
    VisualVM远程监控Java
    centos搭建git服务
  • 原文地址:https://www.cnblogs.com/gaizhongfeng/p/7568295.html
Copyright © 2011-2022 走看看