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