RoBoLoG

[Python] 파이썬의 메타클래스(MetaClass) 본문

Study/Python

[Python] 파이썬의 메타클래스(MetaClass)

SKJun 2024. 1. 10. 15:02

 

메타클래스란?

메타클래스는 클래스의 클래스입니다. 즉, 메타클래스는 클래스를 생성하고 정의하는 데 사용되는 클래스입니다. 일반적으로 클래스는 객체의 템플릿을 정의하고, 메타클래스는 클래스의 템플릿을 정의합니다. 메타클래스는 클래스 생성 과정에 개입하여 추가적인 로직을 수행할 수 있게 해줍니다. 이를 통해 클래스의 동작을 동적으로 변경하거나 클래스 정의 시점에 특정 작업을 자동화할 수 있습니다.


코드 예시

import functools

def method_logger(func):
    # 메소드 호출 전후에 로그를 출력하는 데코레이터 함수 정의
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        print(f"Logging: {func.__name__} 호출 시작")
        result = func(self, *args, **kwargs)
        print(f"Logging: {func.__name__} 호출 종료")
        return result
    return wrapper

class LoggingMeta(type):
    # 모든 메소드에 로깅 기능을 추가하는 메타클래스 정의
    def __new__(cls, name, bases, dict):
        # 클래스의 모든 메소드를 순회
        for attr_name, attr_value in dict.items():
            if callable(attr_value):
                # 메소드를 로깅 데코레이터로 래핑
                dict[attr_name] = method_logger(attr_value)
        return type.__new__(cls, name, bases, dict)

class MyClass(metaclass=LoggingMeta):
    # LoggingMeta 메타클래스를 사용하는 샘플 클래스 정의
    def method1(self):
        print("메소드 1 실행")

    def method2(self, value):
        print(f"메소드 2 실행: {value}")
  • LoggingMeta 메타클래스의 __new__ 메서드가 호출됩니다. 이 메서드는 MyClass가 정의될 때 실행됩니다. 이 메서드는 MyClass에 정의된 모든 메소드를 순회하고, 각 메소드를 method_logger 데코레이터 함수로 래핑합니다.

 

instance = MyClass()
  • MyClass의 인스턴스를 생성합니다. 이 과정에서 메타클래스는 직접적으로 관여하지 않습니다.

 

instance.method1()

 

  • instance.method1()을 호출하면, 먼저 method_logger에 의해 "Logging: method1 호출 시작"이 출력되고, 실제 메소드 method1이 실행되어 "메소드 1 실행"이 출력됩니다. 그 후 "Logging: method1 호출 종료"가 출력됩니다.

 

instance.method2(100)
  • instance.method2(100)을 호출하면, 비슷한 과정으로 "Logging: method2 호출 시작", "메소드 2 실행: 100", 그리고 "Logging: method2 호출 종료"가 순서대로 출력됩니다.
728x90
반응형