“Dekorator Python” Kode Jawaban

Dekorator 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

Dekorator 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

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

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

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

Dekorator 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

Jawaban yang mirip dengan “Dekorator Python”

Pertanyaan yang mirip dengan “Dekorator Python”

Lebih banyak jawaban terkait untuk “Dekorator Python” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya