Menu
CoddyTech

容器魔术方法

本课属于 Coddy Python 学习旅程的“面向对象编程”单元。第 35 课,共 64 课。

容器魔术方法可以让你的类像内置容器(列表、字典等)一样运行。它们让自定义对象支持索引、检查长度和迭代。

下面是一个包含容器魔术方法的类示例:

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

__len__ 方法让 len() 可以正常使用:

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

__getitem__ 方法支持通过索引获取元素:

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

__setitem__ 方法支持通过索引赋值:

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

__contains__ 方法让 in 运算符生效:

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

__iter__ 方法支持迭代:

for item in my_list:
    print(item)

输出:

4
3
1
10
True
False
1
10
3
4

要点:像 __len__、__getitem__、__setitem__、__iter__ 和 __contains__ 这样的容器魔术方法,可以让你自定义的类表现得像内置容器一样。这样,你的对象就能支持直观的索引、迭代和成员测试。

challenge icon

挑战

中等

在这个挑战中,你将实现一个 Deck 类,用于模拟一副扑克牌,并实现全面的功能,同时遵循 Python 的惯例。

你只需要编辑 deck.py 文件。按照代码中的 TODO 注释,逐步实现以下内容:

  • 初始化一副标准的 52 张牌(使用类似 "2H"、"KD"、"AS" 的字符串)
  • 支持 Python 内置操作:
    • 索引访问(deck[0])
    • 长度检查(len(deck))
    • 迭代(for card in deck)
    • 成员测试("AS" in deck)
  • 实现 shuffle 方法,随机打乱牌的顺序

亲手试试

from deck import Deck

# 综合测试用例处理
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()
    
    # 测试能否访问第一张和最后一张牌
    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"
    
    # 测试负数索引
    assert deck[-1] == deck[51], "Negative indexing should work correctly"
    
    # 测试访问超出范围的位置
    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"
    
    # 确认指定的牌存在
    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]
    
    # 第一次洗牌
    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"
    
    # 顺序很可能已经改变(但也有极小的概率没变)
    different_order = (original_order != first_shuffle)
    
    # 再洗一次牌,确保顺序改变
    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()
    
    # 测试所有有效的牌是否都在牌组中
    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"
    
    # 测试无效的牌是否都不在牌组中
    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()
    
    # 测试迭代
    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}"
    
    # 测试多次迭代
    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!")

# 根据输入运行相应的测试
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:
    # 默认测试:运行原有的测试套件
    def test_deck():
        try:
            # 测试初始化和长度
            deck = Deck()
            assert len(deck) == 52, f"Deck should have 52 cards, but has {len(deck)}"
            
            # 测试 getitem
            first_card = deck[0]
            assert isinstance(first_card, str), f"Card should be a string, but got {type(first_card)}"
            
            # 测试 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"
            
            # 测试迭代
            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"
            
            # 测试 shuffle(基本检查:顺序是否发生变化)
            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"
            
            # 检查 shuffle 是否会丢失卡牌
            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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Python 在线编译器