zoukankan      html  css  js  c++  java
  • python装饰器参数那些事_接受参数的装饰器

    # -*- coding: utf-8 -*-
    #coding=utf-8
    '''
    @author: tomcat
    @license: (C) Copyright 2017-2019, Personal exclusive right.
    @contact: liliang07@yungengxin.com
    @software: coding
    @file: decorator1.py
    @time: 2019/7/26 11:25
    '''
    
    '''
    接受参数的解释器
    
    '''
    import inspect
    def log(text):
        def decorator(func):
            def wrapper(*args,**kwargs):
                print("text={},name={}".format(text,func.__name__))
                res=func(*args,**kwargs)
                return res
            return wrapper
        return decorator
    
    @log('excuse')
    def add(x,y):
        return  x + y
    print(add(3,4))
    
    '''
    接受参数的解释器
    '''
    def outer_decorator(*outer_args,**outer_kwargs):
    
        def decorator(fn):
            def decorated(*args,**kwargs):
                decorator_args = inspect.getcallargs(outer_decorator, *outer_args, **outer_kwargs)
                print("outer_args={},outer_kwargs={},decorator_args={},func_name={}".format(outer_args, outer_kwargs,decorator_args,outer_decorator.__name__))
                decorated_args = inspect.getcallargs(fn, *args, **kwargs)
                res=fn(*args, **kwargs)
                print("arg={},keord={},decorated_args={},func_name={}".format(args, kwargs, decorated_args,fn.__name__))
                return res
            return decorated
        return decorator
    
    @outer_decorator(1,2,"test",test1=2)
    def foo(a,b,c):
        return  a+b+c
    
    print(foo(1,6,c=6))
    def f (a ,b=1,*pos,**named):
        print("say hello")
    print(inspect.getcallargs(f, 1, 2, 4,3,t="test"))
    

      

      

    text=excuse,name=add
    7
    outer_args=(1, 2, 'test'),outer_kwargs={'test1': 2},decorator_args={'outer_args': (1, 2, 'test'), 'outer_kwargs': {'test1': 2}},func_name=outer_decorator
    arg=(1, 6),keord={'c': 6},decorated_args={'a': 1, 'b': 6, 'c': 6},func_name=foo
    13

    {'a': 1, 'b': 2, 'pos': (4, 3), 'named': {'t': 'test'}}

  • 相关阅读:
    SSM——事务配置
    SSM——Spring+Mybtis整合(代理【mapper】开发模式)
    objective-c(五)关于代码块的使用
    objective-c(四)内存管理
    objective-c(三)类与对象的方法调用
    objective-c(二)基本数据类型介绍
    objective-c(一)关于基本数据类型打印输出方式
    Eclipse启动发生的错误:An internal error occurred during: "Initializing Java Tooling".
    单例模式
    Java 代理模式
  • 原文地址:https://www.cnblogs.com/tallme/p/11249613.html
Copyright © 2011-2022 走看看