Answers for "how does a decorator work in 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
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

def deco(func):
    def wrap(s):
        d = {}
        for i in s:
            d[i] = s.count(i)
        func(s)
        return d
    return wrap

@deco
def count(stng):
    return stng
mystring = "scorpio"  
print(count(mystring))
Posted by: Guest on June-28-2021

Code answers related to "how does a decorator work in python"

Python Answers by Framework

Browse Popular Code Answers by Language