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

Python类实例循环赋值异常:UNO反转卡牌批量创建问题

UNO卡牌创建问题解决

问题核心原因

你只创建了一个Card实例,循环过程中只是反复修改这个实例的colour属性,然后把同一个实例的引用重复添加到reverse_cards列表里。由于列表里的所有元素指向的都是同一个Card对象,最后一次循环修改的yellow会覆盖之前的颜色值,导致输出全是[reverse, yellow]。

解决方案

方案1:循环内创建新实例

每次循环都生成一个新的Card对象,确保每个元素都是独立的实例:

class Card:
  def __init__(self, symbol, colour, is_action_card = False, is_wild_card = False):
    self.symbol = symbol
    self.colour = colour
    self.is_action_card = is_action_card
    self.is_wild_card = is_wild_card

  def __repr__(self):
    return "{symbol}, {colour}".format(symbol=self.symbol, colour=self.colour)


colour_list = ["red", "green", "blue", "yellow"]
reverse_cards = []

for colour in colour_list:
    # 每次循环创建新的Card实例
    reverse_card = Card("reverse", colour, True)
    reverse_cards.append([reverse_card])

print(reverse_cards)
# 输出 [[reverse, red], [reverse, green], [reverse, blue], [reverse, yellow]]

方案2:用生成函数简化逻辑

如果需要批量生成同类型卡牌,可以封装一个生成函数,让代码更简洁:

class Card:
  def __init__(self, symbol, colour, is_action_card = False, is_wild_card = False):
    self.symbol = symbol
    self.colour = colour
    self.is_action_card = is_action_card
    self.is_wild_card = is_wild_card

  def __repr__(self):
    return "{symbol}, {colour}".format(symbol=self.symbol, colour=self.colour)

def create_action_card(symbol, colour):
    return Card(symbol, colour, is_action_card=True)

colour_list = ["red", "green", "blue", "yellow"]
# 用列表推导式批量生成
reverse_cards = [[create_action_card("reverse", c)] for c in colour_list]

print(reverse_cards)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:10:39