본문 바로가기
Python 문법/Python 기본 문법(3.10 기준)

[python3.10 기본] 18. 고급 함수

by cogito21_python 2024. 7. 2.
반응형

18.1 데코레이터

데코레이터는 함수를 인자로 받아, 그 함수에 새로운 기능을 추가한 후 반환하는 함수입니다. 데코레이터를 사용하면 코드의 반복을 줄이고, 함수의 동작을 변경할 수 있습니다.

 

기본 데코레이터

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

인자를 받는 데코레이터

def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                func(*args, **kwargs)
        return wrapper
    return decorator_repeat

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

18.2 클로저

클로저는 함수 내부에서 정의된 함수가 외부 함수의 변수를 참조하는 구조입니다. 클로저를 사용하면 외부 함수의 상태를 유지하면서 내부 함수를 사용할 수 있습니다.

 

클로저 예제

def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

hello_func = outer_function("Hello")
hello_func()  # Hello

18.3 고차 함수 (map, filter, reduce)

고차 함수는 하나 이상의 함수를 인자로 받고, 함수를 반환할 수도 있는 함수입니다.

 

map 함수

def square(x):
    return x * x

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))  # [1, 4, 9, 16, 25]

filter 함수

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))  # [2, 4, 6]

reduce 함수
reduce 함수는 functools 모듈에서 제공됩니다.

from functools import reduce

def add(x, y):
    return x + y

numbers = [1, 2, 3, 4, 5]
sum = reduce(add, numbers)
print(sum)  # 15

18.4 functools 모듈

functools 모듈은 고급 함수 기능을 제공하는 여러 유용한 도구를 포함합니다.

 

partial 함수: 인자의 일부를 고정하여 새로운 함수를 생성합니다.

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
print(square(3))  # 9

wraps 데코레이터: 데코레이터를 정의할 때 원래 함수의 메타데이터를 유지합니다.

from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("Calling decorated function")
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def say_hello():
    """This is a simple greeting function."""
    print("Hello!")

print(say_hello.__name__)  # say_hello
print(say_hello.__doc__)   # This is a simple greeting function.

 

반응형