📜  装饰器在Python中打印函数调用详细信息

📅  最后修改于: 2022-05-13 01:55:46.209000             🧑  作者: Mango

装饰器在Python中打印函数调用详细信息

Python中的装饰器是一种设计模式,它允许用户向现有对象添加新功能,而无需修改其结构。装饰器通常在定义用户想要装饰的函数之前调用。

例子:

# defining a decorator 
def hello_decorator(func): 
    
    # inner1 is a Wrapper function in  
    # which the argument is called 
        
    # inner function can access the outer local 
    # functions like in this case "func" 
    def inner1(): 
        print("Hello, this is before function execution") 
    
        # calling the actual function now 
        # inside the wrapper function. 
        func() 
    
        print("This is after function execution") 
            
    return inner1 
    
    
# defining a function, to be called inside wrapper 
def function_to_be_used(): 
    print("This is inside the function !!") 
    
    
# passing 'function_to_be_used' inside the 
# decorator to control its behavior 
function_to_be_used = hello_decorator(function_to_be_used) 
    
    
# calling the function 
function_to_be_used() 
输出:
Hello, this is before function execution
This is inside the function !!
This is after function execution

注意:有关详细信息,请参阅Python中的装饰器

装饰器打印函数调用详细信息

让我们考虑一个场景,您编写了非常长的代码并想知道函数调用的详细信息。因此,您可以做的是每次滚动浏览您的代码,以了解不同的功能以了解它们的详细信息,或者您可以巧妙地工作。您可以创建一个可以打印您想要的任何函数的详细信息的装饰器。

为此, Python中的某些属性的函数。一种这样的属性是__code__ ,它返回被调用的函数字节码。 __code__属性还具有某些有助于我们执行任务的属性。我们将使用co_varnames属性返回参数名称和局部变量的元组,以及co_argcount返回参数数量(不包括仅关键字参数,* 或 ** args)。让我们看看使用这些讨论过的属性的这种装饰器的以下实现。

例子:

# Decorator to print function call
# details
def function_details(func):
      
      
    # Getting the argument names of the
    # called function
    argnames = func.__code__.co_varnames[:func.__code__.co_argcount]
      
    # Getting the Function name of the
    # called function
    fname = func.__name__
      
      
    def inner_func(*args, **kwargs):
          
        print(fname, "(", end = "")
          
        # printing the function arguments
        print(', '.join( '% s = % r' % entry
            for entry in zip(argnames, args[:len(argnames)])), end = ", ")
          
        # Printing the variable length Arguments
        print("args =", list(args[len(argnames):]), end = ", ")
          
        # Printing the variable length keyword
        # arguments
        print("kwargs =", kwargs, end = "")
        print(")")
          
    return inner_func
  
  
# Driver Code
@function_details
def GFG(a, b = 1, *args, **kwargs):
    pass
  
GFG(1, 2, 3, 4, 5, d = 6, g = 12.9)
GFG(1, 2, 3)
GFG(1, 2, d = 'Geeks')
输出:
GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {'d': 6, 'g': 12.9})
GFG (a = 1, b = 2, args = [3], kwargs = {})
GFG (a = 1, b = 2, args = [], kwargs = {'d': 'Geeks'})