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

Python报错AttributeError:int对象无insert属性的原因及解决

问题分析与解决

错误原因

  • player = deal_card()这行代码中,deal_card()返回的是单个整数(卡牌数值),因此player是整数类型,而非你预期的列表。
  • insert()、append()是列表专属的方法,整数对象没有这些属性;add()是集合的方法,同样不适用于整数,所以调用这些方法都会触发AttributeError。

修复方案

需要先将player初始化为列表,再向其中添加卡牌:

完整修复代码

import random  # 必须导入random模块,否则无法使用random.choice

def deal_card():
    """Returns a random card from the deck."""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card

# 初始化player为包含第一张卡牌的列表
player = [deal_card()]
# 追加第二张卡牌到列表末尾(符合发牌逻辑)
player.append(deal_card())
# 可继续追加更多卡牌
player.append(deal_card())

print(player)  # 输出示例:[2, 3, 5]

补充说明

  • 如果需要在指定位置插入卡牌(比如列表开头),可以使用insert():
    player.insert(0, deal_card())  # 在索引0的位置插入新卡牌
    
  • 不要忘记导入random模块,否则原代码会触发NameError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:27:30