Python Decorators

python decorator
Photo by Kevin Ku on Unsplash

What are functions in Python??

def say_hi:
print("Hi")
# say_hi() Output: Hi
print(say_hi == say_hi2)# Output: True
print(say_hi)# Output: <function say_hi at 0x00000152AE323D30>print(say_hi2)# Output: <function say_hi at 0x00000152AE323D30>
def say_hi():
print("Hi")
def say_hello():
print("Hello")
def greet(func):
return func
greet(say_hi)()greet(say_hello)()
Hi
Hello
def greet():def say_hi():
print("Hi")
def say_hello():
print("Hello")
say_hi()
say_hello()
greet()
Hi
Hello

What is python decorators??

Basic Syntax of Decorator

def simple_decorator(func):
print("Before function call....")
func()
print("After function call....")
return func
def say_hi():
print("Hi")
say_Hi = simple_decorator(say_hi)
Before function call....
Hi
After function call....

Create a Simple Decorator

def simple_decorator(func):
print("Before function call....")
func()
print("After function call....")
return func
@simple_decorator
def say_hi():
print("Hi")
Before function call....
Hi
After function call....

Multiple Decorators

Class based decorators

--

--

Software Developer | Machine Learning Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store