아래는 데이터 카드를 관리하기 위한 데이터 카드 컨테이너를 구현한 사용자 정의 클래스의 샘플 코드입니다. 이 클래스는 여러 데이터 카드를 저장하고, 검색 및 필터링 등의 기능을 제공합니다.
from datetime import datetime
from typing import List, Optional, Dict
class DataCard:
"""데이터 카드 클래스"""
def __init__(self, name: str, description: str, tags: Optional[List[str]] = None):
self.name = name
self.description = description
self.created_at = datetime.now()
self.updated_at = datetime.now()
self.tags = tags or []
def update_description(self, new_description: str):
self.description = new_description
self.updated_at = datetime.now()
def add_tag(self, tag: str):
if tag not in self.tags:
self.tags.append(tag)
self.updated_at = datetime.now()
def remove_tag(self, tag: str):
if tag in self.tags:
self.tags.remove(tag)
self.updated_at = datetime.now()
def display(self):
print(f"Data Card: {self.name}")
print(f"Description: {self.description}")
print(f"Created At: {self.created_at}")
print(f"Updated At: {self.updated_at}")
print(f"Tags: {', '.join(self.tags)}")
class DataCardContainer:
"""데이터 카드 컨테이너 클래스"""
def __init__(self):
self.cards: List[DataCard] = []
def add_card(self, card: DataCard):
"""컨테이너에 데이터 카드 추가"""
if any(existing_card.name == card.name for existing_card in self.cards):
raise ValueError(f"A card with the name '{card.name}' already exists.")
self.cards.append(card)
def remove_card(self, card_name: str):
"""컨테이너에서 데이터 카드 삭제"""
self.cards = [card for card in self.cards if card.name != card_name]
def get_card(self, card_name: str) -> Optional[DataCard]:
"""이름으로 데이터 카드 검색"""
for card in self.cards:
if card.name == card_name:
return card
return None
def filter_by_tag(self, tag: str) -> List[DataCard]:
"""특정 태그를 포함한 데이터 카드 필터링"""
return [card for card in self.cards if tag in card.tags]
def display_all(self):
"""모든 데이터 카드 출력"""
if not self.cards:
print("No data cards available.")
for card in self.cards:
card.display()
print("-" * 40)
# 사용 예제
if __name__ == "__main__":
# 데이터 카드 생성
card1 = DataCard(name="Customer Data", description="Contains customer demographics.", tags=["customer", "demographics"])
card2 = DataCard(name="Sales Data", description="Sales performance data.", tags=["sales", "performance"])
card3 = DataCard(name="Survey Data", description="Customer feedback survey results.", tags=["survey", "feedback"])
# 컨테이너 생성 및 카드 추가
container = DataCardContainer()
container.add_card(card1)
container.add_card(card2)
container.add_card(card3)
# 모든 카드 출력
print("All Data Cards:")
container.display_all()
# 특정 카드 검색
print("\nSearching for 'Sales Data':")
sales_card = container.get_card("Sales Data")
if sales_card:
sales_card.display()
# 특정 태그로 필터링
print("\nFiltering cards with tag 'customer':")
customer_cards = container.filter_by_tag("customer")
for card in customer_cards:
card.display()
코드 설명
- DataCard 클래스:
- 각 데이터 카드를 표현하며 이름, 설명, 태그, 생성/수정 시간을 포함.
- 태그 추가/삭제 및 설명 업데이트 기능 제공.
- DataCardContainer 클래스:
- 여러 데이터를 관리할 컨테이너로, 다음 주요 기능 포함:
- 카드 추가: 이름이 중복되지 않도록 확인.
- 카드 삭제: 이름으로 특정 카드를 삭제.
- 카드 검색: 이름으로 특정 카드 반환.
- 태그 필터링: 특정 태그를 포함한 카드 목록 반환.
- 전체 출력: 저장된 모든 데이터 카드를 출력.
- 여러 데이터를 관리할 컨테이너로, 다음 주요 기능 포함:
- 사용 예제:
- 세 개의 데이터 카드를 생성하고 컨테이너에 추가.
- 모든 카드 출력, 특정 카드 검색, 특정 태그로 필터링.
실행 결과 (예시):
All Data Cards:
Data Card: Customer Data
Description: Contains customer demographics.
Created At: 2025-01-07 12:00:00.123456
Updated At: 2025-01-07 12:00:00.123456
Tags: customer, demographics
----------------------------------------
Data Card: Sales Data
Description: Sales performance data.
Created At: 2025-01-07 12:00:01.123456
Updated At: 2025-01-07 12:00:01.123456
Tags: sales, performance
----------------------------------------
Data Card: Survey Data
Description: Customer feedback survey results.
Created At: 2025-01-07 12:00:02.123456
Updated At: 2025-01-07 12:00:02.123456
Tags: survey, feedback
----------------------------------------
Searching for 'Sales Data':
Data Card: Sales Data
Description: Sales performance data.
Created At: 2025-01-07 12:00:01.123456
Updated At: 2025-01-07 12:00:01.123456
Tags: sales, performance
Filtering cards with tag 'customer':
Data Card: Customer Data
Description: Contains customer demographics.
Created At: 2025-01-07 12:00:00.123456
Updated At: 2025-01-07 12:00:00.123456
Tags: customer, demographics
이 클래스 구조는 여러 데이터 카드를 체계적으로 관리하고 쉽게 검색, 필터링, 업데이트할 수 있도록 설계되었습니다.
'데이터 카드 자료구조' 카테고리의 다른 글
[데이터 카드 자료구조] 히스토리 메타클래스 샘플 코드 (0) | 2025.01.07 |
---|---|
[데이터 카드 자료구조] 히스토리 보조 카드 샘플 코드 (0) | 2025.01.07 |
[데이터 카드 자료구조] 메타정보를 표현하는 샘플 코드 (0) | 2025.01.07 |
[데이터 카드 자료구조] 리스트 상속 데이터 카드 자료구조 2 (1) | 2024.10.29 |
[데이터 카드 자료구조] 데이터 카드 자료구조의 필터 기능 3 (0) | 2024.10.29 |