“décorateur python” Réponses codées

décorateur 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")
Busy Batfish

décorateur de python

from functools import wraps
def debug(func):
    @wraps(func)
    def out(*args, **kwargs):
        print('hello world')
        return func(*args, **kwargs)
    return out

@debug
def add(x, y):
    return x + y
Thom626

décorateurs à 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
King Generous

décorateurs à Python

# this functon converts any string into uppercase
def deco(function):
    def wrap(s):
        return s.upper()
        function(s)
    return wrap

@deco
def display(s):
    return s 
print(display("not bad"))
King Generous

Décorateurs à Python

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]
Rakesh Meher

décorateur python

#a decoratoradds a bahavior to an existing function or class  
#it uses the @ sign plus name of decoorator on a line above a function to be decorated
# e.g. here is aDecorator that is a wrapper function 
def aDecorator(func):     #func is the wrapped function
   def wrapper(*args, **kwargs):
      ret = func(*args, **kwargs)  #get reault of wrapped function
      return f' Decorator has converted result to upper-case: {ret.upper()} '
   return wrapper          #wrapper contains the decoration and result of wrapped function 

@aDecorator                # aDecorator is the wrapper function
def exampleFunction():
   return "basic output"   #lower-case string

print(exampleFunction())   #addDecoration adds note and converts to Upper-case

#Output:
#  Decorator has converted result to upper-case: BASIC OUTPUT 
ruperto2770

Réponses similaires à “décorateur python”

Questions similaires à “décorateur python”

Plus de réponses similaires à “décorateur python” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code