데이터 카드에 푸터 카드를 생성하기 위한 메타클래스를 작성하여 클래스가 정의될 때 자동으로 공통 푸터 정보를 설정하도록 할 수 있습니다. 푸터는 일반적으로 데이터에 대한 요약 정보나 최종 수정 기록을 포함하는 데 사용됩니다.


푸터 카드 메타클래스 코드

from datetime import datetime

class FooterMeta(type):
    """푸터 카드를 생성하는 메타클래스"""
    def __new__(cls, name, bases, dct):
        # 푸터 정보 기본값 추가
        dct.setdefault("__footer__", {
            "last_updated": datetime.now(),
            "summary": f"Default footer for {name}.",
        })
        return super().__new__(cls, name, bases, dct)

    def update_footer(cls, key, value):
        """푸터 정보 업데이트"""
        if "__footer__" in cls.__dict__:
            cls.__footer__[key] = value
            cls.__footer__["last_updated"] = datetime.now()  # 마지막 업데이트 시간 갱신
        else:
            raise AttributeError("Footer not defined in the class.")

    def get_footer(cls):
        """푸터 정보 가져오기"""
        return cls.__footer__

class DataCard(metaclass=FooterMeta):
    """푸터 카드를 포함하는 데이터 카드"""
    def __init__(self, name, data):
        self.name = name
        self.data = data

    def display(self):
        """데이터 카드 정보 출력"""
        print(f"Data Card: {self.name}")
        print(f"Data: {self.data}")

    @classmethod
    def display_footer(cls):
        """푸터 정보 출력"""
        print("Footer Information:")
        for key, value in cls.__footer__.items():
            print(f"  {key}: {value}")

# 사용 예제
if __name__ == "__main__":
    # 기본 푸터 확인
    print("Default Footer:")
    DataCard.display_footer()

    # 푸터 업데이트
    DataCard.update_footer("summary", "This is a summary of the data card.")
    DataCard.update_footer("notes", "Footer metadata added.")

    print("\nUpdated Footer:")
    DataCard.display_footer()

    # 데이터 카드 생성
    card = DataCard(name="Sample Data", data={"key": "value"})
    print("\nCard Details:")
    card.display()

코드 설명

  1. FooterMeta 메타클래스:
    • 클래스 정의 시 __footer__라는 공통 푸터를 자동으로 생성.
    • 기본 푸터는 마지막 업데이트 시간(last_updated)과 간단한 요약(summary)을 포함.
    • update_footer 메서드: 푸터의 특정 항목을 수정하고, 마지막 업데이트 시간을 자동 갱신.
    • get_footer 메서드: 현재 클래스의 푸터 정보를 반환.
  2. DataCard 클래스:
    • FooterMeta 메타클래스를 기반으로 작성된 데이터 카드 클래스.
    • 클래스 수준에서 푸터 정보를 관리하며, 인스턴스 데이터와는 분리.
  3. 사용 예제:
    • 기본 푸터를 확인하고, update_footer 메서드를 사용하여 푸터 값을 수정.
    • 데이터 카드를 생성하여 데이터와 푸터를 각각 출력.

실행 결과 (예시):

Default Footer:
Footer Information:
  last_updated: 2025-01-07 12:00:00.123456
  summary: Default footer for DataCard.

Updated Footer:
Footer Information:
  last_updated: 2025-01-07 12:01:00.123456
  summary: This is a summary of the data card.
  notes: Footer metadata added.

Card Details:
Data Card: Sample Data
Data: {'key': 'value'}

주요 기능

  • 푸터 자동 생성: 클래스 정의 시 기본 푸터가 자동으로 설정.
  • 푸터 업데이트 가능: 클래스 수준에서 푸터 정보를 동적으로 수정 가능.
  • 자동 갱신: 푸터가 업데이트될 때 마지막 수정 시간이 자동으로 갱신.
  • 클래스와 인스턴스 데이터 분리: 푸터는 클래스 수준에서 관리하며, 인스턴스 데이터와 독립적.

이 메타클래스는 데이터 카드에 공통적인 요약 정보나 변경 기록을 추가하여 관리하는 데 적합하며, 클래스의 관리 효율성을 높여줍니다.

+ Recent posts