how to use decorators in python code example
Example 1: decorator python
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")
Example 2: decorators in python
'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)
Example 3: python decorators
# 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()
Example 4: python decorator
#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
Example 5: examples of function decorators in Python
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
# Output: addition_func was called
Example 6: how to use lambda in java
StateOwner stateOwner = new StateOwner();
stateOwner.addStateListener(
(oldState, newState) -> System.out.println("State changed")
);