Python Advanced - Use of Universal Decorators

Python Advanced - Use of Universal Decorators Introduction:

Generic Decorator

1. Python Advanced - Use of Universal Decorators.Decorate a function with parameters


# Add the function of output log
def logging( fn ):
def inner( num1, num2):
print("--trying to calculate--")
fn ( num1, num2)
return inner
# Decorate the function with a decorator
@logging
def sum_num ( a , b):
result = a + b
print(result)
sum_num ( 1 , 2)
operation result:
--Working hard to calculate--

2. Python Advanced - Use of Universal Decorators.Decorate functions with return values


# Add the function of output log
def logging( fn ):
def inner( num1, num2):
print("--trying to calculate--")
result = fn ( num1, num2)
return result
return inner
# Decorate the function with a decorator
@logging
def sum_num ( a , b):
result = a + b
return result
result = sum_num ( 1 , 2)
print(result)
operation result:
--Working hard to calculate--

3. Python Advanced - Use of Universal Decorators.Decorate functions with variable-length parameters


# Add the function of output log
def logging( fn ):
def inner( * args , ** kwargs ):
print("--trying to calculate--")
fn ( * args , ** kwargs )
return inner
# Decorate functions with syntactic sugar
@logging
def sum_num ( * args , ** kwargs ) :
result = 0
for value in args :
result += value
for value in kwargs.values ():
result += value
print(result)
sum_num ( 1 , 2, a=10)
operation result:
--Working hard to calculate--

4. Python Advanced - Use of Universal Decorators.Generic Decorators
# Add the function of output log
def logging( fn ):
def inner( * args , ** kwargs ):
print("--trying to calculate--")
result = fn ( * args , ** kwargs )
return result
return inner
# Decorate functions with syntactic sugar
@logging
def sum_num(*args, **kwargs):
result = 0
for value in args:
result += value
for value in kwargs.values():
result += value
return result
@logging
def subtraction(a, b):
result = a - b
result = a - b
print(result)
result = sum_num(1, 2, a=10)
print(result)
subtraction( 4, 2)
operation result:
--Working hard to calculate--
13
--Working hard to calculate--

5. Python Advanced - Use of Universal Decorators Summary
•The syntax of the generic decorator :
# Generic decorator
def logging( fn ):
def inner( * args , ** kwargs ):
print("--trying to calculate--")
result = fn ( * args , ** kwargs )
return result
return inner

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00