Author - StudySection Post Views - 27 views

Explain this pattern with an example in Python – Decorators

In general, each variable has its scope. The global variable is declared outside of the main program block and used by any function as a free variable and the Local variable is declared within the function and bound to its local scope.
As python works with object.Functions are also treated as objects in python. So, many variables can be bound with the same object.

def my_programme(msg):
my_programme("Hello Webner")
new_progamme = my_programme
new_progamme ("Hello Webner")


Hello Webner
Hello Webner

Both my_programme and new_progamme refer to the same object. In general, a function can take other functions as arguments or return another function.

Decorators behave as a wrapper. It takes in a function, adds the functionality, and returns it.

Purpose: to enhance the functionality of code
Working: modify code at compile time.


def my_programme(func):
def new_progamme ():
print("Decorate the function")
return new_progamme
def without_decorate():
print("not decorated")
decorate = make_decorate(without_decorate)


Decorate the function
not decorated

Explanation: In the above program, make_decorate is a decorator which decorates the without_decorate() function.
Python simplifies this concept using the syntax ‘ @’ with the decorator function which is placed above the function definition to be decorated.
def without_decorate():
print("not decorated")
which is equivalent to :
def without_decorate():
print("not decorated")
decorate = make_decorate(without_decorate)


  • simple syntax.
  • manipulate the functionality of a function.

People having good knowledge of Financial accounting can get an Accounting Certification Exams from StudySection to increase their chances of getting a job in this field. You can get a foundation level certification if you are new to Financial accounting or you can go for advanced level certification if you have expert level skills in Financial accounting.

Leave a Reply

Your email address will not be published.