1def our_decorator(func):
2 def function_wrapper(x):
3 print("Before calling " + func.__name__)
4 func(x)
5 print("After calling " + func.__name__)
6 return function_wrapper
7
8@our_decorator
9def foo(x):
10 print("Hi, foo has been called with " + str(x))
11
12foo("Hi")
13
1#Decorator are just function that take function as first
2#parameter and return a function
3def logging(f):
4 def decorator_function(*args, **kwargs):
5 print('executing '+f.__name__)
6 return f(*args, **kwargs)
7 return decorator_function
8#Use it like this
9@logging
10def hello_world():
11 print('Hello World')
12#calling hello_world() prints out:
13#executing hello_world
14#Hello World
1'pass function which we want to decorate in decorator callable object'
2def our_decorator(func): # func is function to be decorated by decorator
3
4 def wrapper(x): # x is parameter which is passed in func
5 if x%2==0:
6 return func(x)
7 else:
8 raise Exception("number should be even")
9 return wrapper
10
11@ our_decorator
12def func(x): # actual function
13 print(x,"is even")
14func(2)
15func(1)
16
17' if you do not want to use @'
18func=our_decorator(func)
19func(2)
20
21
22
23
1# decorators are user to decorate functions like what to do before/after calling the function
2import time
3
4def delay_decorator(function):
5 def wrapper_function():
6 print("-----------------------I am gonna greet you--------------------------")
7 time.sleep(2)# waits for 2 seconds
8 function() # calls the function
9 time.sleep(1)# waits for 1 sec
10 print("------------------How do you feel about that greet?-------------------")
11 return wrapper_function
12
13@delay_decorator
14def greet():
15 print("Helllllloooooooooo")
16
17greet()
1# Decorator with arguments
2import functools
3
4# First function takes the wanted number of repetition
5def repeat(num_times):
6 # Second function takes the function
7 def decorator_repeat(func):
8 # Third function, the wrapper executes the function the number of times wanted
9 # functools decorator to print the true name of the function passed instead of "wrapper"
10 @functools.wraps(func)
11 def wrapper(*args, **kwargs):
12 for _ in range(num_times):
13 result= func(*args, **kwargs)
14 return result
15 return wrapper
16 return decorator_repeat
17
18# Our function using the decorator
19@repeat(num_times= 3)
20def greet(name):
21 print(f"Hello {name}")
22
23greet("thomas")
1# This function take input from user and return
2# list of 0 and 1, zero represents odd number
3# and 1 represents even number
4def deco(func):
5 def wrap(lst):
6 x = [1 if i % 2 == 0 else 0 for i in lst]
7 return x
8 func(lst)
9 return wrap
10
11@deco
12def display(l):
13 return (l)
14
15a = [int(x) for x in input("Enter number of elements : ").split(",")]
16print(display(a))