Logo
Unit 5 – Decorators

Decorators

Duration: 5 minutes

Welcome back, Pythonistas on the rise! Are you ready for a new and intriguing Python topic? Today we’re delving into the enigma of Python’s ‘Decorators,’ an important component of Python’s distinct appeal. Let’s get started! Decorators enable us to wrap another function in order to extend the behavior of the wrapped function without affecting it permanently. Functions are first-class objects in Python. This means that functions, like any other object (string, int, float, list, and so on), can be passed around and used as arguments. Here’s a basic Python decorator:

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()

@my_decorator’ is used in this example to ‘decorate’ the function ‘say_hello()’. This may appear confusing at first, but don’t worry! The concept will become much more apparent with practice.

Exercise

Got the gist of decorators? Great! Now it’s your turn:- Define a decorator that prints “Function started” before calling a function and “Function ended” after calling it.

  • Decorate a simple function that prints “Inside the function”.

Conclusion

You’ve now unlocked yet another Python utility - Decorators! They are one of the “magic” aspects that contribute to Python’s power and flexibility. Remember that learning to code is like riding an exciting rollercoaster. Continue on, and you’ll discover more of Python’s amazing potential. Keep up the good work, Pythonista!

Next Tutorial: Generators

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!