Answers for "decorators with example"

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
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

Python Answers by Framework

Browse Popular Code Answers by Language