요약
- 메타클래스는 클래스 생성시점의 동작을 제어하고 메서드나 속성을 동적으로 추가/변경할 때 사용
본문
- 메타 클래스는 1950~ 60년대 초기 인공지능 연구와 함께 등장함
- 메타클래스의 목적은 생성시점의 동작을 제어하고 메서드나 속성을 추가/변경을 동적으로 하고 싶을 때 사용
class User:
def __init__(self, name, age):
if not isinstance(name, str):
raise ValueError("name must be a string")
if not isinstance(age, int):
raise ValueError("age must be an integer")
self.name = name
self.age = age
class Product:
def __init__(self, name, price):
if not isinstance(name, str):
raise ValueError("name must be a string")
if not isinstance(price, float):
raise ValueError("price must be a float")
self.name = name
self.price = price
class ValidationMeta(type):
def __new__(cls, name, bases, attrs):
orig_init = attrs.get('__init__')
def __init__(self, *args, **kwargs):
for attr, attr_type in self.__annotations__.items():
if not isinstance(kwargs.get(attr), attr_type):
raise ValueError(f"{attr} must be of type {attr_type}")
if orig_init:
orig_init(self, *args, **kwargs)
attrs['__init__'] = __init__
return super().__new__(cls, name, bases, attrs)
class User(metaclass=ValidationMeta):
name: str
age: int
class Product(metaclass=ValidationMeta):
name: str
price: float
추상 클래스와 차이
- 메타 클래스는 "생성과 동작 방식을 제어할 수 있음"
참고
python MetaClass 다중상속 문제