Menu
Coddy logo textTech

Magiczne metody kontenerów

Część sekcji Programowanie obiektowe ścieżki Python w Coddy. Lekcja 35 z 64.

Metody specjalne kontenerów pozwalają Twoim klasom zachowywać się jak wbudowane kontenery (listy, słowniki itp.). Umożliwiają indeksowanie, sprawdzanie długości i iterowanie po Twoich niestandardowych obiektach.

Oto przykład klasy z magicznymi metodami kontenera:

class CustomList:
    def __init__(self, items):
        self.items = items
    
    def __len__(self):
        return len(self.items)
    
    def __getitem__(self, index):
        return self.items[index]
    
    def __setitem__(self, index, value):
        self.items[index] = value
    
    def __iter__(self):
        return iter(self.items)
    
    def __contains__(self, item):
        return item in self.items

Metoda __len__ sprawia, że działa len():

my_list = CustomList([1, 2, 3, 4])
print(len(my_list))  # 4

Metoda __getitem__ umożliwia indeksowanie w celu pobierania elementów:

print(my_list[2])    # 3
print(my_list[0])    # 1

Metoda __setitem__ umożliwia przypisywanie za pomocą indeksowania:

my_list[1] = 10
print(my_list[1])    # 10

Metoda __contains__ sprawia, że operator in działa:

print(3 in my_list)     # True
print(100 in my_list)   # False

Metoda __iter__ umożliwia iterację:

for item in my_list:
    print(item)

Wynik:

4
3
1
10
True
False
1
10
3
4

Kluczowa kwestia: Metody specjalne kontenerów, takie jak __len__, __getitem__, __setitem__, __iter__ i __contains__, sprawiają, że Twoje własne klasy zachowują się jak wbudowane kontenery. Dzięki temu obiekty obsługują intuicyjne indeksowanie, iterację i sprawdzanie przynależności.

challenge icon

Wyzwanie

Średni

W tym wyzwaniu zaimplementujesz klasę Deck, która symuluje talię kart do gry, zapewniając pełną funkcjonalność i zgodność z konwencjami języka Python.

Musisz edytować tylko plik deck.py. Postępuj zgodnie z komentarzami TODO w kodzie, które poprowadzą Cię przez implementację:

  • Inicjalizacji standardowej talii 52 kart (z użyciem ciągów znaków takich jak "2H", "KD", "AS")
  • Obsługi wbudowanych operacji języka Python:
    • Indeksowanie (deck[0])
    • Sprawdzanie długości (len(deck))
    • Iteracja (for card in deck)
    • Sprawdzanie przynależności ("AS" in deck)
  • Metody shuffle, która losowo zmienia kolejność kart

Spróbuj swoich sił

from deck import Deck

# Kompleksowa obsługa przypadków testowych
test_case = input()

def test_basic_functionality():
    deck = Deck()
    assert len(deck) == 52, f"Deck should have 52 cards, but has {len(deck)}"
    
    first_card = deck[0]
    assert isinstance(first_card, str), f"Card should be a string, but got {type(first_card)}"
    
    assert "AS" in deck, "Ace of Spades should be in the deck"
    assert "XY" not in deck, "XY is not a valid card and should not be in the deck"
    
    cards = [card for card in deck]
    assert len(cards) == 52, f"Iteration should yield 52 cards, but got {len(cards)}"
    
    original_first_five = [deck[i] for i in range(5)]
    deck.shuffle()
    shuffled_first_five = [deck[i] for i in range(5)]
    assert original_first_five != shuffled_first_five or len(deck) <= 5, "Shuffle should change card order"
    
    print("Basic functionality tests passed!")

def test_edge_cases():
    deck = Deck()
    
    # Sprawdź dostęp do pierwszej i ostatniej karty
    first_card = deck[0]
    last_card = deck[51]
    assert isinstance(first_card, str) and isinstance(last_card, str), "First and last cards should be strings"
    
    # Sprawdź indeksowanie ujemne
    assert deck[-1] == deck[51], "Negative indexing should work correctly"
    
    # Sprawdź dostęp poza zakresem
    try:
        invalid_card = deck[52]
        print("Test failed: Should raise IndexError for out of bounds access")
    except IndexError:
        print("Edge case test passed: IndexError raised for out of bounds access")
    
    print("Edge case tests passed!")

def test_card_uniqueness():
    deck = Deck()
    cards = [card for card in deck]
    unique_cards = set(cards)
    
    assert len(unique_cards) == 52, f"All cards should be unique, but found {len(unique_cards)} unique cards"
    
    # Sprawdź, czy określone karty istnieją
    expected_cards = ["2H", "10S", "KD", "AC"]
    for card in expected_cards:
        assert card in deck, f"Expected card {card} not found in deck"
    
    print("Card uniqueness tests passed!")

def test_shuffle_behavior():
    deck = Deck()
    original_order = [card for card in deck]
    
    # Pierwsze tasowanie
    deck.shuffle()
    first_shuffle = [card for card in deck]
    assert len(first_shuffle) == 52, "Shuffle should preserve all 52 cards"
    assert set(first_shuffle) == set(original_order), "Shuffle should not add or remove cards"
    
    # Najprawdopodobniej kolejność się zmieniła (choć istnieje niewielka szansa, że tak się nie stało)
    different_order = (original_order != first_shuffle)
    
    # Drugie tasowanie dla pewności
    deck.shuffle()
    second_shuffle = [card for card in deck]
    different_order_2 = (first_shuffle != second_shuffle)
    
    assert different_order or different_order_2, "Multiple shuffles should change the order"
    
    print("Shuffle behavior tests passed!")

def test_contains_behavior():
    deck = Deck()
    
    # Sprawdź, czy wszystkie prawidłowe karty są w talii
    suits = ['H', 'D', 'C', 'S']
    ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
    
    for suit in suits:
        for rank in ranks:
            card = rank + suit
            assert card in deck, f"Valid card {card} should be in the deck"
    
    # Sprawdź, czy nieprawidłowych kart nie ma w talii
    invalid_cards = ["1H", "11S", "XD", "AX", "JX", ""]
    for card in invalid_cards:
        assert card not in deck, f"Invalid card {card} should not be in the deck"
    
    print("Contains behavior tests passed!")

def test_iteration_behavior():
    deck = Deck()
    
    # Sprawdź iterację
    card_count = 0
    for card in deck:
        card_count += 1
        assert isinstance(card, str), f"Each card should be a string, but got {type(card)}"
    
    assert card_count == 52, f"Iteration should yield 52 cards, but got {card_count}"
    
    # Sprawdź wielokrotne iteracje
    first_iteration = [card for card in deck]
    second_iteration = [card for card in deck]
    assert first_iteration == second_iteration, "Multiple iterations should yield the same order"
    
    print("Iteration behavior tests passed!")

# Uruchom odpowiedni test na podstawie danych wejściowych
if test_case == "basic_functionality":
    test_basic_functionality()
elif test_case == "edge_cases":
    test_edge_cases()
elif test_case == "card_uniqueness":
    test_card_uniqueness()
elif test_case == "shuffle_behavior":
    test_shuffle_behavior()
elif test_case == "contains_behavior":
    test_contains_behavior()
elif test_case == "iteration_behavior":
    test_iteration_behavior()
else:
    # Test domyślny — uruchom oryginalny zestaw testów
    def test_deck():
        try:
            # Przetestuj inicjalizację i długość
            deck = Deck()
            assert len(deck) == 52, f"Deck should have 52 cards, but has {len(deck)}"
            
            # Przetestuj getitem
            first_card = deck[0]
            assert isinstance(first_card, str), f"Card should be a string, but got {type(first_card)}"
            
            # Przetestuj contains
            assert "AS" in deck, "Ace of Spades should be in the deck"
            assert "XY" not in deck, "XY is not a valid card and should not be in the deck"
            
            # Sprawdź iterację
            cards = [card for card in deck]
            assert len(cards) == 52, f"Iteration should yield 52 cards, but got {len(cards)}"
            assert len(set(cards)) == 52, "All cards in the deck should be unique"
            
            # Przetestuj shuffle (podstawowe sprawdzenie, czy kolejność się zmienia)
            original_first_five = [deck[i] for i in range(5)]
            deck.shuffle()
            shuffled_first_five = [deck[i] for i in range(5)]
            assert original_first_five != shuffled_first_five or len(deck) <= 5, "Shuffle should change card order"
            
            # Sprawdź, czy shuffle nie powoduje utraty kart
            assert len(deck) == 52, f"Deck should still have 52 cards after shuffle, but has {len(deck)}"
            
            print("All tests passed!")
        except AssertionError as e:
            print(f"Test failed: {e}")

    test_deck()
    print("Tests completed")
quiz iconSprawdź się

Ta lekcja zawiera krótki quiz. Zacznij lekcję, żeby na niego odpowiedzieć i śledzić swoje postępy.

Wszystkie lekcje w sekcji Programowanie obiektowe

Poćwicz samodzielnie: Kompilator Python online