A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.
In [ ]:
# sandwich()
# test = bread(ingredients(Cheese))
# test()
# # bread_1 = ingredients(Cheese)
# # print(bread_1)
# # bread_1()
In [7]:
def bread(test_funct):
def hyderabad():
print("</''''''\>")
test_funct()
print("<\______/>")
return hyderabad
def ingredients(test_funct):
def chennai():
print("#tomatoes#")
test_funct()
print("~salad~")
return chennai
def cheese(food="--Say Cheese--"):
print(food)
In [8]:
ch = bread(cheese)
inn = bread(ingredients(cheese))
ch()
print("^"*20)
inn()
In [9]:
@bread
@ingredients
def sandwich(food="--Say Cheese--"):
print(food)
sandwich()
!!! Order Matters !!!
In [10]:
@ingredients
@bread
def sandwich(food="--Say Cheese--"):
print(food)
sandwich()
In [11]:
@bread
@ingredients
def hotdog(food="Jam"):
print(food)
hotdog()
In [12]:
def Names(test_funct):
def inner():
print("{Hello}")
print("\tA-Priya")
print("\tManish Gupta")
print("\tNeha", end="\n\t")
test_funct()
print("(/Hello}")
return inner
@Names
def print_AShanti():
print("A-Shanti")
print_AShanti()
In [10]:
def names(test_funct):
def inner():
print("\t", name)
test_funct()
return inner()
def Hello(test_funct):
def inner():
print("{Hello}")
print("\tA-Priya")
print("\tManish Gupta")
print("\tNeha", end="\n\t")
test_funct()
print("(/Hello}")
return inner
@Hello
@names(name="Mayank")
def print_AShanti():
print("A-Shanti")
print_AShanti()
In [22]:
class A(object):
def method(*argv):
return argv
a = A()
a.method
Out[22]:
In [23]:
a.method('an arg')
Out[23]:
In [24]:
class A(object):
@staticmethod
def method(*argv):
return argv
a = A()
a.method
Out[24]:
When we call a static method we don’t get any additional arguments.
In [25]:
a.method('an arg')
Out[25]:
In [3]:
class A(object):
@classmethod
def method(*argv):
return argv
a = A()
a.method
Out[3]:
In [2]:
a.method('an arg')
Out[2]:
In [3]:
def test(strg):
print("Name: ", strg)
def hello(func, name):
print("Ja")
func(name)
hello(test, "Mayank")
In [4]:
class B(object):
@classmethod
def method(*argv):
return argv
In [5]:
a = B()
a.method()
Out[5]: