상세 컨텐츠

본문 제목

Decorators

Python

by techbard 2024. 12. 23. 08:41

본문

반응형
# Decorators
# ==========

# Decorator func
def printer(func):
    def wrapper(*args, **kwargs):
        print("Before calling {func.__name__}()...")
        func(*args, **kwargs)
        print("After calling {func.__name__}()...")
    return wrapper

# func to be decorated
def say_hello(name: str):
    print(f"Hello, {name}")

# say_hello("John")

# method 1. Create another function
say_to_person = printer(say_hello)
say_to_person("John")

# method 2. Decorate the function deinition
@printer
def say_hello2(name: str):
    print(f"Hello, {name}")

say_hello2("Mike")

# Decorators Use Cases
# ====================
# Logging: Automatically log information when a function is called.
# Authentication: Check user credentials before executing a function.
# Timing: Measure the time a function takes to execute.
# Caching: Stor results of expensive function calls and reuse them
# when the same inputs occur again.

# Output:
Before calling {func.__name__}()...
Hello, John
After calling {func.__name__}()...
Before calling {func.__name__}()...
Hello, Mike
After calling {func.__name__}()...

 

# Functions within Functions

def hello(name='Jose'):
    def greet():
        return '\t This indise the greet() function'

    def welcome():
        return '\t This indise the welcome() function'

    if name == 'Jose':
        return greet
    else:
        return welcome
        
x = hello()
print(x())

# Output:
This inside the greet() function

 

# Functions as Arguments
def hello():
    return "Hi! Jose!"

def other(func):
    print("Other code goes here!")
    print(func())
 
other(hello)
  
# Output:
Other code goes here!
Hi! Jose!

 

# Wrap Function

def new_decorator(func):
    def wrap_func():
        print("Code here, before executing the func")
        func()
        print("Code here will execute after the func()")
    return wrap_func
    
def func_needs_decorator():
    print("This function needs a decorator!")
    
func_needs_decorator = new_decorator(func_needs_decorator)
func_needs_decorator()

# Output:
Code here, before executing the func
This function needs a decorator!
Code here will execute after the func()

 

# 장식자 표기법을 사용해서 수동으로 데코레이터 할당을 대신함

def new_decorator(func):
    def wrap_func():
        print("Code here, before executing the func")
        func()
        print("Code here will execute after the func()")
    return wrap_func
    
@new_decorator
def func_needs_decorator():
    print("This function needs a decorator!")

func_needs_decorator()

# Output:
Code here, before executing the func
This function needs a decorator!
Code here will execute after the func()

 

반응형

관련글 더보기

댓글 영역