获取无类型和无效文字错误

Posted

技术标签:

【中文标题】获取无类型和无效文字错误【英文标题】:Getting None Type and Invalid Literal Errors 【发布时间】:2021-11-10 21:20:06 【问题描述】:

我正在尝试创建一个二十一点游戏,并且我正在学习数据类装饰器以获得更简洁的代码。我目前正在测试这些课程,但我遇到了几个错误。代码如下:

from dataclasses import dataclass, field    
import random
from typing import List
import itertools

RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()

SUITS = '♣ ♢ ♡ ♠'.split()


@dataclass
class Card:
"""Card Class for single card identification and for determining Ace value"""

    rank: str
    suit: str

    def __str__(self):
        return f"self.rank of self.suit"


@dataclass()    
class Player:
""" Player class for creating any # of players, give them a name/hand/bank """

    name: str
    values: int = 0
    # hand is a list of cards with an initial DEFAULT value of None
    hand: List[Card] = None
    # DEFAULT VALUES MUST BE STATED
    bank: int = 0

    def compute_card_value(self, card):
    # J, Q, K needs to be a rank of 10 check a specified list of all       
        possible card ranks
        if card in ["J", "Q", "K"]:
            value = 10
    # if value of hand is over 10 then value of ace = 1, else it will = 11
        elif card == "A":
            if self.values > 10:
                value = 1
            else:
                value = 11
        else:
        # numerical value for individual card which is passed as an argument/input
            value = int(card.rank)
        return value

    def add_card_to_hand(self, card):
        self.hand.append(card)
        self.values += self.compute_card_value(card)

    @dataclass()
    class Dealer(Player):
    
    """Dealer will need to be able to have their own hand, and display only the second card after initial deal"""
    
        def show_dealer_hand(self):
        return f"Dealer is showing self.hand[0]"


""" Using itertools to define a function to create a deck out of existing global variables RANKS & SUITS"""

def new_deck():    
    new_deck = [Card(r, s) for r, s in itertools.product(RANKS, SUITS)]
    return new_deck    


@dataclass()
class Deck:
    """Deck will create a deck with all normal deck ranks/suits in a list. Shuffle deck. Deal one card. Also return str """

    all_cards: List[Card] = field(default_factory=new_deck)

    def shuffle_deck(self):
        random.shuffle(self.all_cards)

    def deal_card(self):
        return self.all_cards.pop(0)

    def __repr__(self):
        str_cards = ", ".join([str(card) for card in self.all_cards])
        return str_cards

blkjck_deck = Deck()
blkjck_deck.shuffle_deck()

alex = Player("Alex", bank=200)

dealer = Dealer("Dealer")

list_of_players = []

for _ in range(2):
    new_card = blkjck_deck.deal_card()
    dealer.add_card_to_hand(new_card)

print(dealer.hand)

### 我试着发一些牌给庄家。我得到:

Traceback (most recent call last):
  File "C:/Users/abala/PycharmProjects/Milestone_2_Blackjack/main_2.py", line 94, in <module>
    dealer.add_card_to_hand(new_card)
  File "C:/Users/abala/PycharmProjects/Milestone_2_Blackjack/main_2.py", line 48, in add_card_to_hand
    self.hand.append(card)
AttributeError: 'NoneType' object has no attribute 'append'

如果我将手牌(玩家等级)更改为没有 None 类型的基本列表,当一张或两张牌是 J、Q、K 或 A 时,我开始收到其他错误:

Traceback (most recent call last):
  File "C:/Users/abala/PycharmProjects/Milestone_2_Blackjack/main_2.py", line 98, in <module>
    dealer.add_card_to_hand(new_card)
  File "C:/Users/abala/PycharmProjects/Milestone_2_Blackjack/main_2.py", line 53, in add_card_to_hand
    self.values += self.compute_card_value(card)
  File "C:/Users/abala/PycharmProjects/Milestone_2_Blackjack/main_2.py", line 48, in compute_card_value
    value = int(card.rank)
ValueError: invalid literal for int() with base 10: 'A'

请让我知道我在这里没有得到什么。

【问题讨论】:

hand: List[Card] = Noneself.hand 初始化为None。您应该将其初始化为一个空列表 我试过了,我开始在原帖底部遇到第二个问题。 【参考方案1】:

要修复第一个错误,你需要将Player.hand初始化为一个空列表,而不是None

    hand: List[Card] = []

要解决第二个问题,您的if 语句应该检查card.rank,而不是card,以检测它是否是一张人脸卡片。

    def compute_card_value(self, card):
    # J, Q, K needs to be a rank of 10 check a specified list of all       
        possible card ranks
        if card.rank in ["J", "Q", "K"]:
            value = 10
    # if value of hand is over 10 then value of ace = 1, else it will = 11
        elif card.rank == "A":
            if self.values > 10:
                value = 1
            else:
                value = 11
        else:
        # numerical value for individual card which is passed as an argument/input
            value = int(card.rank)
        return value

【讨论】:

以上是关于获取无类型和无效文字错误的主要内容,如果未能解决你的问题,请参考以下文章

如何修复:ValueError:long() 以 10 为底的无效文字

显示获取的数据问题:对象作为 React 子项/类型错误无效:未定义

在 React Native 中使用组件导入获取错误“元素类型无效预期字符串”

Python中浮点错误的无效文字

MySQL 迁移错误:检测到无效的时间戳文字

Swift UITesting 错误:文字中的转义序列无效。 \U201c