Answers for "method decorator python"

19

decorator python

def our_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        func(x)
        print("After calling " + func.__name__)
    return function_wrapper

@our_decorator
def foo(x):
    print("Hi, foo has been called with " + str(x))

foo("Hi")
Posted by: Guest on September-30-2020
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
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