python - (未列表继承) Deck 类(纸牌游戏)可以在 for 循环中使用,无需 __iter__

标签 python for-loop iteration

伙计们,

几天之内,我只是在考试前做我平常的随机小程序,我决定写一个五张抽奖扑克。由于它只是为了玩一点代码,所以我没有从基本类继承任何内容。我的牌组包含一个列表属性,该属性已被赋予简单的可读性和功能所需的功能:

import random

from card import Card

class Deck():

    def __init__(self):
        self.cards = self.__generate_cards()
        random.shuffle(self.cards)

    def __str__(self):
        cards_str = ""
        for card in self.cards:
            cards_str += str(card)
        return cards_str

    def __getitem__(self,index):
        return self.cards[index]

    def __generate_cards(self):
        cards = []
        for i in range(4):
            for j in range(13):
                cards.append(Card(i,j+1))
        return cards

    def pop(self,index):
        return self.cards.pop(index)

如您所见,没有找到 .__iter__ 方法,这意味着我无法迭代 Deck() 对象,对吗? Python 向我展示了一个不同的故事:由于某种原因,下一个代码会循环遍历 self.cards 中的卡片对象,并实际打印卡片,而不需要迭代器:

deck = Deck()
for card in deck:
    print(card)    # cards have a __str__ method

对我来说没有多大意义,除非它是 python 魔法的一部分,给任何对象一个可能循环的机会。 ;p 谁能用这个来向我展示一下光吗?提前致谢!

最佳答案

Why does defining __getitem__ on a class make it iterable in python?

这是一个向后兼容的东西。拥有 __getitem__ 使其可迭代。

关于python - (未列表继承) Deck 类(纸牌游戏)可以在 for 循环中使用,无需 __iter__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12044970/

相关文章:

python - 在不知道输出数组大小的情况下像matlab一样在python中连接数组

c - 循环不执行 C 中最后一次迭代中的最后一条语句?

python - 如何在循环中从生成器获取一组三个下一个值

python - 在 Django 中获取本地系统时间

python - numpy:沿除最后一个轴之外的所有轴求和

python - 使用 matplotlib Slider 创建具有不同非等距参数的交互式绘图

python - 创建具有相同键的字典列表?

bash - Linux 外壳 : for arg; do

c++ - 如何在 C++ 中遍历日期范围

javascript - 使用javascript从html表中删除元素