You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错TypeError:__str__返回非字符串,my_hand无法添加元素求助

Python卡牌程序的TypeError与显示问题解决

问题描述

反复触发TypeError,报错信息如下:

Traceback (most recent call last):
File "C:\Users\baris\PycharmProjects\pythonProject2\main.py", line 60, in 
print(my_hand)
TypeError: __str__ returned non-string (type NoneType)

同时误以为my_hand无法添加元素,完整代码如下:

class Card(object):
    RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    SUITS = ["D", "S", "H", "C"]

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        rep = self.rank + self.suit
        return str(rep)


class Hand(object):
    """a hand of playing cards"""
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep += str(card) + "  "
        else:
            rep = "<empty>"
            return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)


card1 = Card(rank="A", suit="c")
print(card1)
card2 = Card(rank="2", suit="c")
card3 = Card(rank="3", suit="c")
card4 = Card(rank="4", suit="c")
card5 = Card(rank="5", suit="c")
print(card2)
print(card3)
print(card4)
print(card5)

my_hand = Hand()
print("my hand before i add cards\n", my_hand)
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print("my hand after adding 5 cards: ")
print(my_hand)

your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print("your hand: ")
print(your_hand)
print("my hand: ")
print(my_hand)

my_hand.clear()
print("my hand now: ")
print(my_hand)

问题原因与解决方法

核心问题

Hand类的__str__方法存在逻辑错误:

  • 当self.cards不为空时,代码构建了卡牌字符串rep,但没有执行return rep语句,导致函数默认返回None,这就是触发TypeError的直接原因。
  • 元素其实已经成功添加到my_hand中,只是因为__str__方法无法正确返回字符串,导致打印时出错,让你误以为添加失败。

修正后的__str__方法

def __str__(self):
    if self.cards:
        rep = ""
        for card in self.cards:
            rep += str(card) + "  "
        return rep  # 补充返回语句
    else:
        return "<empty>"

优化写法(可选)

用join方法简化字符串拼接,代码更简洁高效:

def __str__(self):
    return "  ".join(str(card) for card in self.cards) if self.cards else "<empty>"

修改后,程序就能正常打印手牌内容,add、give等方法的功能也能正常体现。

内容的提问来源于stack exchange,提问作者Baris Yolci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:15:19