不可迭代的值 self.hand 用于迭代上下文

问题描述 投票:0回答:2

我正在开发一个可用于玩二十一点(Python)的 Discord 机器人。下面的代码应该计算各手牌的值:

class Player(object):
    def __init__(self, id=''):
        self.id = id
        self.hand = None
        self.status_text = ''
        self.bet = 0
        self.value = 0
        self.score = 0
        self.wins = 0
        self.no_response = 0
        self.request_leave = False
        self.playing = False

    def calculate_value(self):
        """Calculates value of player's hand"""
        if not self.hand:
            return 0
        num_aces = 0
        total_value = 0
        for card in self.hand:
            if pydealer.const.DEFAULT_RANKS['values'][card.value] == 13:
                num_aces += 1
                total_value += 11
            elif pydealer.const.DEFAULT_RANKS['values'][card.value] >= 10:
                total_value += 10
            else:
                total_value += int(card.value)

        while num_aces > 0 and total_value > 21:
                total_value -= 10
                num_aces -= 1
        return total_value

不幸的是我到达了

for card in self.hand:
    if pydealer.const.DEFAULT_RANKS['values'][card.value] == 13:
       num_aces += 1
       total_value += 11

显示错误 Non-iterable value self.hand is using in an iterating context。 我希望有人能帮帮忙!问候并非常感谢。

python discord discord.py bots blackjack
2个回答
0
投票

您的

self.hand
已初始化为
None
。 因此,在使用它运行之前,请确保您的
self.hand
设置为可迭代对象。


0
投票

老问题,但我最近也遇到了这个问题,所以万一其他人这样做:

假设这是 pylint

E1133:not-an-iterable
错误,你只需要给
self.hand
一个类型:
self.hand: list | None = None
。您在迭代之前也正确检查了
if not self.hand
,所以 mypy 也应该感到满意。

© www.soinside.com 2019 - 2024. All rights reserved.