[Python] 9(완). 고급 주제

1. 데코레이터 (Decorators)

파이썬의 데코레이터는 함수에 다른 기능을 추가하는 데 사용되는 패턴으로, 함수나 메서드의 기능을 확장하는 방법입니다. 기존 함수를 수정하기 않고, 추가적인 기능을 덧붙혀 함수 호출 전후에 메시지를 출력합니다.

def my_decorator(func):
    def wrapper():
        print("Function Before Call")
        func()
        print("Function After Call")
    return wrapper

@my_decorator
def say_py():
    print("Hello!, Python World")

say_py()


# Function Before Call
# Hello!, Python World
# Function After Call

2. 제너레이터(Generator)

제너레이터는 이터레이터를 생성하는 방법으로, yield 키워드를 사용해 값을 하나씩 생성합니다. 메모리 효율적이며 큰 데이터 집합을 처리할 때 유용합니다.

def my_generator():
    for i in range(5):
        yield i * 2

for value in my_generator():
    print(value) # 0,2,4,6,8

3.컨텍스트 매니저(Context-Manager)

컨텍스트 매니저는 특정 작업을 시작하고 끝내는 코드로, __enter__와 __exit__메서드를 정의하여 자원을 안전하게 관리할 수 있습니다.

class MyContextManager:
    def __enter__(self):
        print("Context In.")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
         print("Context Exit")

with MyContextManager() as manager:
    print("Context interior")
    
# Context In.
# Context interior
# Context Exit

4. 비동기 프로그래밍

비동기 프로그래밍은 다른 작업이 진행되는 동안 대기할 수 있는 기능을 제공하며, async와 await를 사용하여 비동기 함수를 정의하고 호출합니다.

import asyncio

async def say_hello():
    await asyncio.sleep(1)
    print("Hello, World")

async def main():
    await say_hello()

asyncio.run(main())

5. 메타 프로그래밍

메타프로그래밍은 프로그램 구조를 동적으로 수정하는 기술로, 아래 예제에 메타클래스를 사용해 클래스에 새로운 메서드를 추가해줍니다.

class Meta(type):
    def __new__(cls, name, bases, attrs):
         attrs['greet'] = lambda self: print("Meta's Hello!")
         return super().__new__(cls,name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

obj = MyClass()
obj.greet() # Meta's Hello!

6. 타입 힌트

타입 힌트는 함수의 매개변수와 반환 값의 타입을 명시하는 방법으로, 이는 코드 가독성을 높이고, 정적 분석 도구를 사용하여 타입 관련 오류를 미리 발경하는 데 도움을 줍니다.

def add_numbers(a: int, b: int) -> int:
    return a + b

result = add_numbers(5, 6)
print(result) # 11

 

 

GitHub - Koras02/python-blog

Contribute to Koras02/python-blog development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Python' 카테고리의 다른 글

[Python] 8. 예외 처리  (0) 2025.03.02
[Python] 7. 객체지향 프로그래밍  (0) 2025.02.28
[Python] 6. 파일 입출력  (0) 2025.02.27
[Python] 5. 모듈과 패키지  (0) 2025.02.24
[Python] 4.함수(Function)  (0) 2025.02.22