xxxxxxxxxx
#example of a simple decorator function in Python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("hello!")
say_hello()
# Output: Something is happening before the function is called.
# hello!
# Something is happening after the function is called.
xxxxxxxxxx
"""
I want to make a decorator that prints something before and after every
function it is placed in."""
def printer(func): #This is our decorator that wraps any function it is placed in
def child():
print("fucntion started")
func()
print("function stoped")
return child()
@printer #With this syntax, we can decorate any function we want
def counter():
for i in range(10):
print(i)
xxxxxxxxxx
# decorator function
def outer(func):
def inner():
str1 = func()
return str1.upper() # addition of functionality
return inner
@outer
def print_str():
return "good morning"
print(print_str())
# Output -> 'GOOD MORNING'
# A decorator is a function that takes another function as an argument, adds some kind of functionality to it and returns another function. Python decorators help add functionality to an existing code(function) which may aid in code reusability.
xxxxxxxxxx
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behaviour
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
xxxxxxxxxx
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
# -- the decorator
def held(self, c):
self.add_class(c)
# Decorators have to return the function/class passed (or a modified variant thereof), however I'd rather do this separately than retroactively change add_class, so.
# "held" is more succint, anyway.
return c
def __getitem__(self, n):
return self.classes[n]
food_types = ClassHolder()
@food_types.held
class bacon:
taste = "salty"
@food_types.held
class chocolate:
taste = "sweet"
@food_types.held
class tee:
taste = "bitter" # coffee, ftw ;)
@food_types.held
class lemon:
taste = "sour"
print(food_types['bacon'].taste) # No manual add_class needed! :D