Answers for "built in decorators in python"

7

decorators in python

'pass function which we want to decorate in decorator callable object'
def our_decorator(func):  # func is function to be decorated by decorator
  
  def wrapper(x):       # x is parameter which is passed in func
    if x%2==0:
      return func(x)
    else:
      raise Exception("number should be even")
  return wrapper

@ our_decorator
def func(x):         # actual function 
  print(x,"is even")
func(2)
func(1)

' if you do not want to use @'
func=our_decorator(func)
func(2)
Posted by: Guest on July-21-2020
23

python decorators

# decorators are user to decorate functions like what to do before/after calling the function
import time

def delay_decorator(function):
    def wrapper_function():
        print("-----------------------I am gonna greet you--------------------------")
        time.sleep(2)# waits for 2 seconds
        function()   # calls the function
        time.sleep(1)# waits for 1 sec
        print("------------------How do you feel about that greet?-------------------")
    return wrapper_function

@delay_decorator
def greet():
    print("Helllllloooooooooo")

greet()
Posted by: Guest on March-23-2021
1

decorators in python

#This function take user input for list and returns a tuple cotaining 2 lists
#one of even numbers another of odd numbers
def deco(function):
    def wrap(lst):
        even = []
        odd = []
        for i in lst:
            if i % 2 == 0:
                even.append(i)
            else:
                odd.append(i)
        return even,odd
        function(lst)
    return wrap

@deco
def display(lst):
    print(lst)


a = [int(x) for x in input("Enter number of elements : ").split(",")]
print(display(a))
Posted by: Guest on June-26-2021
0

decorators in python

# This function take input from user and return
# list of 0 and 1, zero represents odd number
# and 1 represents even number
def deco(func):
    def wrap(lst):
        x = [1 if i % 2 == 0 else 0 for i in lst]
        return x
        func(lst)
    return wrap

@deco   
def display(l):
    return (l)

a = [int(x) for x in input("Enter number of elements : ").split(",")]
print(display(a))
Posted by: Guest on June-27-2021
0

decorators in python

def deco(function):
    def wrap(num):
        if num % 2 == 0:
            print(num,"is even ")
        else:
            print(num,"is odd")
        function(num)
    return wrap
    
@deco
def display(num):
    return num
display(9)   # pass any number to check whether number is even or odd
Posted by: Guest on June-25-2021

Python Answers by Framework

Browse Popular Code Answers by Language