Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 14

"""

DECORATORS -
----------

#Adding functionality without changeing the main function is called as Decorators.

OR

#A decorators is a function which takes another function as an argument, add some


extra
#functionality and return another function without altering The source code of
orginal function.

#Decorators also called as META Programming

#reason:-->Apart of the program Tries to modify another part of the program at


compile time.

*GENERAL STRUCTURE OF DECORATOR


-------------------------------

1)A decorators function must be an nested function were in the outer function
must take only one argument (Decorator function address)

2)The nested/inner function must take variable numbers of arguments.

3)The outer function must return the nested/inner function address.

4)The parameters of outer function should be called inside nested function.

def outer (func):


def inner(*args, **kwargs):
print(modified main func)
func(*args, **kwargs)
return inner

@outer
def main_func():
statements
return statement
print(main_func(arguments))

example:------>

1 WADF TO CHECK IF THE 1ST ARGUMENT IS LESSER THAN 2ND ARGUMENT


IF THEN SWAP THEM AND PERFORM DIVISION BUT THE CONDITION IS YOU
SHOULD NOT MODIFY THE ORIGINAL FUNC
# def outer(func): #func= div

# def inner(a,b): #a---> 2 , b ----> 4

# if a<b: #2<4 (True)

# a,b=b,a #2,4=4,2

# return func(a,b) #a=4,b=2 #func()

# return inner

# @outer

# def div(a,b): #a,b ----> parameters #a=4,b=2

# print(a/b) #4/2----> 2.0

# div(2,4) #2,4 ----> arguments

explanation of the above program:---->

"""
1.def outer ----> memory address will be created

2. @outer - div = outer(div)

3. func == div

4. outer () ---> calling ----> controller will go inside

5. def inner()-----> memory address will be created and it will return this address
to the func which made it call

6. div = inner() address

7. next we will call the div (2,4) ----> internally invoking the inner func and
(a---> 2 , b----> 4)

8. if a<b ---> 2<4 (true)

9. it got swapped ---> 2,4=4,2

10. func(4,2) -----> called so it will invoke ----> main func()---> div(4,2)

11. then it will perform the statement inside the main function ---> div()
a/b ----> 4/2 -----> 2.0

note - div()-----> inner function will get evoked


func() -------> the main function will get evoked
"""
#2. WADF TO ADD 2 NUMBERS AND DISPLAY THE MESSAGE
# BEFORE AND AFTER PERFORMING THE ADDITION

# def addition(func): #func==add


# def inner(*args):
# print("im performing addition")
# func(*args)
# print("addition is done")
# return inner
# @addition
# def add(*args):
# c=sum(args)
# print(c)
# add(1,2,3,4,5,3,4,6,8)

explanation of the above program:---->

"""
1. def addition -----> address is get created

2. @addition - add = addition(add)

3. func= add

4. addition () -----> calling -----> control will go inside the addition ()

5. def inner() ------> memory address will be created and it will return to the
func which called it

6. add = inner() address

7. add() ----> called ----> internally it is invoking the inner func()

8. all the values you passed when calling the add () will go store in the inner
(*args)

9. next it will print "im performing addition"

10. next we are calling the func(*args) ------> func== add()

11. add(*args) ----> it will perform sum of all the arguments it is getting stored
in variable "c"

12. printing c ----> addition of all the arguments

13. controller will go inside the inner() and it will print the next line which is
"addition performed"

note - add() it will invoke inner func()


when you call the func() the main function will get invoked
"""
#3. CREATE A DECORATOR TO RETURN ONLY POSITIVE OUT FROM ANY SUBTRACTION

# def outer(func):
# def inner(*args,**kwargs):
# res = func(*args,**kwargs) #res = -22
# return (abs(res))
# return inner
# @outer
# def sub(a,b):
# return a-b
# print(sub(-20,2))

explanation of the above program:---->

"""
1. def outer () ----> memory address will be created

2. @outer - sub = outer(sub)

3. func == sub

4. outer() -----> will be called ---> controller will go inside

5. def inner () ----> memory address will be created and it will return to the func
which made it call

6. sub = inner () address

7. sub(-20,2)----> sub() will invoke inner func(args = -20 , 2)

8. func() called ----> it will invoke main function ---> sub(-20,2)

9. it will perform the action ---> a-b ----> -20-2----> -22 , since you are
returning the value

10 . it will go and stores in res

11. abs(-22)---> 22 -----> res it will come to the main function and print it out

"""

#4. WAP TO CREATE A DECORATOR FUNCTION THAT MESURES


# THE EXECUTION TIME OF THE FUNCTION AND PRINT IT

# from time import sleep

# def outer(func):

# def inner():

# start= time.time() #current laptop time


# func() #func is called

# end = time.time() #again it will take the laptop time

# execution_time = end-start

# print(f"{func.__name__} took {execution_time} seconds")

# return inner
#
# @outer
# def display():
# sleep(3)
# for i in range(1,10):
# ...
# display()

explanation of the above program:---->

"""
1. def outer () ----> memory address will be created

2. @outer - display= outer(display)

3. func == display

4. outer() -----> will be called ---> controller will go inside

5. def inner () ----> memory address will be created and it will return to the func
which made it call

6. display = inner () address

7.display() ---> is been called so it will invoke the inner function

8. once the controller comes inside the inner func()--->start= time.time()


#current laptop time it will take and store it in start variable

9. func() ---> called so it will invoke the main func

10. before executing the statements inside the main function it is sleeping for 3
seconds

11. for loop will execute ----> then end = time.time() again it will take the
laptop time and store it in end variable

12. execution time - end - start ----> it will gove the execution time

13. func.__name__ ----> here we have used __name__ magic method because we want
the function name
"""

#5. WRITE A DECORATIVE FUNCTION TO PRINT THE TYPE OF DATATPE BEFORE


# PERFORMING THE ACTION
# def outer(func):
# def inner(*args,**kwargs):
# for i in args:
# print(type(i))
# func(*args,**kwargs)
# return inner
# @outer
# def display(*args):
# print(sum(args))
# display(2,3)

explanation of the above program:---->

"""
1. def outer () ----> memory address will be created
2. @outer - display= outer(display)
3. func == display
4. outer() -----> will be called ---> controller will go inside
5. def inner () ----> memory address will be created and it will return to the func
which made it call
6. display = inner () address
7. display() ----> call and arguments will be passed (2,3) and internally it is
invoking the inner func() arguments will be stored in *args
8. for i in args ---> it will traverse inside the args which will be in tuple form
9. next it will print the type of (i)
10. func is called which will invoke the display func()
11. it will come inside the func and it will sum the args ---->(2,3)
"""

#6. WAP TO SUM THE POSITIONAL ARGUMENTS AND GET THE LENGTH OF THE KEYWORD ARGUMENTS

# def pos_key_modify(func):
# def wrapper(*args,**kwargs):
# print(f"the total sum of args are : {sum(args)}")
# func(*args,**kwargs)
# return wrapper
# @pos_key_modify
# def pos_key(*args,**kwargs):
# print(f"the length of keyword arguments are : {len(kwargs)}")
# pos_key(2,4,5,a=1,b=2,c=3)

explanation of the above program:---->

"""
1. def pos_key_modify() ----> memory address will be created
2. @pos_key_modify - pos_key= pos_key_modify(pos_key)
3. func == pos_key
4. pos_key_modify() -----> will be called ---> controller will go inside
5. def wrapper() ----> memory address will be created and it will return to the
func which made it call
6. pos_key = wrapper() address
7. pos_key(2,4,5,a=1,b=2,c=3) it is called ----> invoking the wrapper ()
8. print(f"the total sum of args are : {sum(args)}") ----> this will get executed
giving output --> 10
9. func() ---> called it invokes the pos_key
10 print(f"the length of keyword arguments are : {len(kwargs)}")---> this will get
executed giving out ---> 3
"""

#7. WADF TO DO ARTHEMATIC OPERATIONS ON THE GIVEN NUMBER AND THE CONDITION IS A>B
THEN PERFORM MULTIPLICATION IN DECORATOR FUNCTION ELSE CUBE IT IN DECORATOR

# def outer(func):
# def inner(a,b):
# if a>b:
# print(f"performing multiplication {a*b}")
# else:
# print(f"performing cubing of the number {a**3}, {b**3}")
# func(a,b)
# return inner
#
# @outer
# def arth(a,b): #a=5 , b=3 if a>b
# print(f"performing addition {a+b}") #8
# print(f"performing subtraction {a-b}") #2
# arth(5,3)

explanation of the above program:---->

"""
1. def outer () ----> memory address will be created
2. @outer - arth= outer(display)
3. func == arth
4. outer() -----> will be called ---> controller will go inside
5. def inner () ----> memory address will be created and it will return to the func
which made it call
6. arth = inner () address
7. arth ---> called and arguments will be passed (5,3) ---> inner function will get
invoked inner(a,b) ---> a=5 , b=3
8. if condition will check if a>b ---> condition is true
9. it will print (a*b)
10. func(5,3) ---> called ---> it will invoke arth (5,3)
11. addition and subtraction will be performed and printed
"""

"""
2. DELAY DECORATORS
--------------------
"""

#1. WADF TO CHECK HOW MUCH TIME IT IS TAKING TO PERFORM EACH TASK
#I WILL BE PERRFORM TWO TASK

#2 MAIN FUNCTIONS ----> DECORATED BY STANDARD DECORATOR

# from time import sleep


# def outer(func):
# def inner(*args,**kwargs): #args=2,4 , args=4,5
# start= time.time()
# sleep(2)
# func(*args,**kwargs)
# end=time.time()
# print(end-start)
# return inner
#
# @outer
# def add(a,b):
# print(f"addition of two numbers is {a+b}")
# add(2,4)
#
# @outer
# def sub(a,b):
# print(f"subtraction of two numbers is {a-b}")
# sub(4,5)

#2. WADF TO DELAY FOR 3 SECOUNDS AND DISPLAY THE NAME


# , DELAY FOR 3 SECONDS AND DISPLAY EMAIL ADDRESS ,
# DELAY FOR 3 SECONDS AND DISPLAY PHONE NUMBER

# print("EMPLOYEE DETAILS")
# def outer(func):
# def inner(*args,**kwargs):
# sleep(3)
# func(*args,**kwargs)
# return inner
#
# @outer
# def display_name():
# res = input("enter the employee name :")
# print(f" EMPLOYEE NAME : {res}")
#
# @outer
# def display_email():
# res1 = input("enter the employee email :")
# print(f" EMPLOYEE EMAIL : {res1}")
#
# @outer
# def display_phno():
# res2 = int(input("enter the employee phone number :"))
# print(f" EMPLOYEE PHONE NUMBER : {res2}")
# display_name()
# display_email()
# display_phno()

#3. WAP TO CREATE A DECORATOR TO WHICH PRINTS


# THE NAME OF THE CALLED FUNCTION ALONG WITH IT SHOULD
# CHECK IF THE NUMBER IS EVEN OR ODD

# def outer(func):
# def inner(*args,**kwargs):
# print(f"the decorated function is {func.__name__}")
# res = func(*args,**kwargs)
# return res
# return inner
#
# @outer
# def display(num):
# if num % 2 ==0: #1% 2 == 0
# return "num is even"
# else:
# return "num is odd"
# print(display(1))
# print(display(2))

#4.wadf to count number of arguments passed to a function

# def count_(func):
# def wrapper(*args):
# print(f"number of arguments passed to a function :{len(args)}")
#
# func(*args)
#
# return wrapper
#
# @count_
# def add_(a,b,c,d,e):
# print(a+b+c+d+e)
#
# add_(1,2,3,4,5)

5..wadf to input 5 seconds before executing function?


# import time
# def delay(func):
# def inner(*args):
# time.sleep(3)
# func(*args)
# return inner
# @delay
#
# def even():
# for i in range(1,11):
# time.sleep(2)
# print(i)
# even()

#6. wadf to print "Guys Respond" message before executing any function by useing
#multiple calls.
#
# import time
# def message(func):
# def inner(*args):
# print("guys respond")
# func(*args)
# return inner
#

# @message
# def mul(a,b):
# time.sleep(5)
# print("mul",a*b)
# mul(10,2)
#

# @message
# def div(a,b):
# time.sleep(5)
# print("div",a/b)
# div(10,2)
#

# @message
# def add(a,b):
# time.sleep(5)
# print("add",a+b)
#
# add(10,2)

#7..wadf to print a message "Enter OTP" to confirm "before doing Tranction and
#withdrawal.

# def confirm(func):
# def tranction(*args):
# print("enter otp to confirm")
# func(*args)
# return tranction
#
# @confirm
# def withdrawal(amount):
# print(f"you have withdrawal rs.{amount}")
# withdrawal(5000)
# @confirm
# def balance(amount):
# print(f"the current balance is rs.{amount}")
# balance(10)
#
# @confirm
# def c_pin(pin):
# print(f"succesfully changed your pin {pin}")
# c_pin(1432)

multiple decorators:----->

# def guys(func):
# def inner(*args):
# print("good morning guys") #decorator func1
# func(*args)
# return inner
#

# def student(func):
# def wrapper(*args):
# print("good night") #decorator func2
# func(*args)
# return wrapper
#

# def python(func):
# def display(*args):
# print("its rainy day")
# func(*args)
# return display
#

# @guys
# @student
# @python

# def greet():
# print("good evening") #main function
# greet()

# def PIN(func):
# def inner (*args):
# Pin=eval(input("Enter PIN"))
# func(*args)
# return inner()

# @PIN
# def Tranction():
# print("your cash is 200")
# @PIN
# def Balance():
# print("Your balance is 1000")
#

# @PIN
# def Pinchange():
# print("PIN changed")

#write a multilevel decorators to accept username and register number of


#employee.

# def log(func):
# def inner(*args,**kwargs):
# print("i am logging")
# func(*args,**kwargs)
# return inner
#
# def register(func):
# def wrapper(*args,**kwargs):
# print("i have registered")
# func(*args,**kwargs)
# return wrapper

# @log
# @register

#
# def Employee(name,reg):
# print(name,reg)
# name=eval(input("pass name:"))
# reg=eval(input("pass email id"))

# Employee(name,reg)

# pass name:"rekha"
# pass email id"rekha@143gmail.com"

output:-->

# i am logging
# i have registered
# rekha rekha@143gmail.com

You might also like