Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Tutorial for Beginners 49 - Python Decorators- https://youtu.be/o77mO0ZOzkIIn this Python Programming Tutorial for Beginners video I am going to show you How to use decorators in Python.
def decorator_func(func):
def wrapper_func():
print('X' * 20)
func()
print('Y' * 20)
return wrapper_func
@decorator_func
def say_hello():
print('Hello World')
#hello = decorator_func(say_hello)
#hello()
say_hello()
# ----------------------------------------------------
def decorator_X(func):
def wrapper_func():
print('X' * 20)
func()
print('X' * 20)
return wrapper_func
def decorator_Y(func):
def wrapper_func():
print('Y' * 20)
func()
print('Y' * 20)
return wrapper_func
@decorator_X
@decorator_Y
def say_hello_again():
print('Hello World')
#hello = decorator_X(decorator_Y(say_hello_again))
#hello()
say_hello_again()
def decorator_divide(func):
def wrapper_func(a, b):
print('divide ', a, ' and ', b)
if b == 0:
print('division with zero is not allowed')
return 0
return a / b
return wrapper_func
@decorator_divide
def divide(x, y):
return x / y
print(divide(15, 0))
from time import time
def timing(func):
def wrapper_func(*args, **kwargs):
start = time()
print(start)
result = func(*args, **kwargs)
end = time()
print(end)
print('Elapsed time: {}'.format(end - start))
return result
return wrapper_func
@timing
def my_func(num):
sum = 0
for i in range(num+1):
sum += i
return sum
print(my_func(20000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.