Author - StudySection Post Views - 80 views
Python

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.

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

Output:

Hello Webner
Hello Webner

Explanation:
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:
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.

Example:

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

Output:

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.
@make_decorate
def without_decorate():
print("not decorated")
which is equivalent to :
def without_decorate():
print("not decorated")
decorate = make_decorate(without_decorate)

Benefits:

  • 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. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri