For any queries you can reach us at / WhatsApp us: +919158876092

What is Decorators in Python

What is Decorators in Python?

A decorator in Python in any callable Python object that is used to modify a function or a class. It takes in a function, adds some functionality, and returns it.

Decorators are a very powerful and useful tool in Python since it allows programmers to modify/control the behavior of function or class. Decorators are usually called before the definition of a function you want to decorate.

There are two different kinds of decorators in Python:

  • Function decorators
  • Class decorators


def test_decorator(func):
	def function_wrapper(x):
		print("Before calling " + func.__name__)
		res = func(x)
		print("After calling " + func.__name__)
	return function_wrapper

def sqr(n):
	return n ** 2


Before calling sqr
After calling sqr