Metodi magici dei contenitori
Fa parte della sezione Programmazione orientata agli oggetti del percorso Python di Coddy. Lezione 35 di 64.
I metodi magici dei contenitori consentono alle tue classi di comportarsi come contenitori integrati (liste, dizionari ecc.). Permettono di indicizzare, controllare la lunghezza e iterare sui tuoi oggetti personalizzati.
Ecco un esempio di una classe con metodi magici di contenitore:
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.itemsIl metodo __len__ fa funzionare len():
my_list = CustomList([1, 2, 3, 4])
print(len(my_list)) # 4Il metodo __getitem__ consente di recuperare gli elementi tramite indicizzazione:
print(my_list[2]) # 3
print(my_list[0]) # 1Il metodo __setitem__ consente di assegnare tramite indicizzazione:
my_list[1] = 10
print(my_list[1]) # 10Il metodo __contains__ fa funzionare l'operatore in:
print(3 in my_list) # True
print(100 in my_list) # FalseIl metodo __iter__ consente l’iterazione:
for item in my_list:
print(item)Output:
4
3
1
10
True
False
1
10
3
4Punto chiave: i metodi magici dei contenitori come __len__, __getitem__, __setitem__, __iter__ e __contains__ fanno sì che le tue classi personalizzate si comportino come i contenitori integrati. Questo offre ai tuoi oggetti un’indicizzazione intuitiva, l’iterazione e la verifica dell’appartenenza.
Sfida
MedioIn questa sfida, implementerai una classe Deck che simula un mazzo di carte da gioco con funzionalità complete e nel rispetto delle convenzioni Python.
Devi modificare solo il file deck.py. Segui i commenti TODO nel codice, che ti guidano nell'implementazione di:
- Inizializzazione di un mazzo standard di 52 carte (usando stringhe come "2H", "KD", "AS")
- Supporto per le operazioni integrate di Python:
- Indicizzazione (
deck[0]) - Verifica della lunghezza (
len(deck)) - Iterazione (
for card in deck) - Verifica dell'appartenenza (
"AS" in deck)
- Indicizzazione (
- Un metodo
shuffleper mescolare le carte
Provalo tu
from deck import Deck
# Gestore completo dei casi di test
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()
# Verifica l'accesso alla prima e all'ultima carta
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"
# Verifica l'indicizzazione negativa
assert deck[-1] == deck[51], "Negative indexing should work correctly"
# Verifica l'accesso oltre i limiti
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"
# Verifica che siano presenti carte specifiche
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]
# Primo mescolamento
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"
# Molto probabilmente l'ordine è cambiato (anche se c'è una piccolissima probabilità che non sia successo)
different_order = (original_order != first_shuffle)
# Secondo mescolamento per maggiore sicurezza
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()
# Verifica che tutte le carte valide siano nel mazzo
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"
# Verifica che le carte non valide non siano nel mazzo
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()
# Verifica l'iterazione
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}"
# Verifica le iterazioni multiple
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!")
# Esegui il test appropriato in base all'input
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 predefinito - esegui la suite di test originale
def test_deck():
try:
# Verifica l'inizializzazione e la lunghezza
deck = Deck()
assert len(deck) == 52, f"Deck should have 52 cards, but has {len(deck)}"
# Verifica getitem
first_card = deck[0]
assert isinstance(first_card, str), f"Card should be a string, but got {type(first_card)}"
# Verifica 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"
# Verifica l'iterazione
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"
# Verifica shuffle (controllo di base che l'ordine cambi)
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"
# Verifica che shuffle non faccia perdere carte
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")Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Programmazione orientata agli oggetti
1Fondamenti di OOP
File esterniIntroduzione a OOPClassi vs. oggettiIl parametro selfMetodiAttributiMetodo costruttore (__init__)Riepilogo - Calcolatrice semplice4Ereditarietà
Ereditarietà di baseLa funzione super()Sovrascrittura dei metodiEreditarietà multiplaOrdine di risoluzione dei metodiRiepilogo - Gerarchia dei dipendenti7Metodi speciali
Introduzione ai metodi magiciSovraccarico degli operatoriMetodi magici dei contenitoriRiepilogo - Lista personalizzata10Modelli di progettazione Parte 1
Introduzione ai modelli di progettazioneModello SingletonModello FactoryModello ObserverModello Strategy2Decoratori
Introduzione ai decoratoriDecoratore di proprietàDecoratore di metodo staticoDecoratore di metodo di classe5Polimorfismo
Ripasso dell'override dei metodiDuck typingClassi e metodi astrattiProgettazione delle interfacceRiepilogo - Calcolatore di forme8Concetti avanzati di OOP
Composizione vs ereditarietàMixinMetodi statici e di classeDecorator di classeContext manager11Pattern di progettazione - Parte 2
Pattern dei comandiPattern adattatorePattern decoratorePattern metodo templatePattern statoPattern composito3Proprietà delle classi
Variabili di istanza e di classeDecorator delle proprietàAttributi privatiRiepilogo - Gestore di conti bancari6Incapsulamento
Membri pubblici, protetti e privatiModificatori di accessoOccultamento delle informazioniDecorator delle proprietà: avanzatiRipasso - Sistema di registri degli studenti12Progetto: Gestione della biblioteca
Panoramica del progettoClassi Libro e UtenteSistema di prestitoFunzionalità di ricercaInterfaccia amministratoreTest e integrazioneEsercitati da solo: Compilatore Python online