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

遍历实例并修改特定实例参数时出现异常

Fixing Dictionary/Array Passing Issues in Your Python RPG Project

Hey there! Let's tackle this common Python gotcha you're running into with passing dictionaries or arrays of items in your RPG course project.

First, let's ground this in your context: you're building an RPG with a Person, Spell, and Item class, running a loop to handle turns for 3 players and 1 enemy in main.py. The problem with passing item collections almost always boils down to how Python handles mutable objects (like lists and dictionaries).

The Root Cause: Pass-by-Reference Behavior

In Python, lists and dictionaries are mutable—meaning their contents can be changed after they're created. When you pass one of these to a function or assign it to an object attribute, you're not sending a brand-new copy of the collection. You're sending a reference to the original collection.

So if you do something like this:

# Create a shared list of potions
party_potions = [Item("Healing Potion", "potion", 50), Item("Mana Potion", "potion", 30)]

# Initialize players with the same list
player1 = Person("Gimli", 150, 30, 25, party_potions)
player2 = Person("Legolas", 120, 60, 20, party_potions)

# Player1 uses a healing potion (removes it from their items)
player1.items.pop(0)

# Uh-oh—player2's potion list is also missing the healing potion now!

Both players are pointing to the exact same list in memory. Changes to one affect all references.

Solutions to Make Independent Collections

1. Shallow Copy for Simple Collections

If your Item instances are immutable (their attributes don't change after creation), a shallow copy is enough. This creates a new list/dictionary, but still references the original Item objects inside.

For lists:

# Use .copy() method
player1 = Person("Gimli", 150, 30, 25, party_potions.copy())

# Or slice the entire list (another way to make a shallow copy)
player2 = Person("Legolas", 120, 60, 20, party_potions[:])

For dictionaries:

item_dict = {"heal": Item("Healing Potion", "potion", 50), "mana": Item("Mana Potion", "potion", 30)}
player1 = Person("Gimli", 150, 30, 25, item_dict.copy())

2. Deep Copy for Mutable Item Objects

If your Item class has mutable attributes (like a quantity that you might modify), you'll need a deep copy. This creates a brand new copy of the collection and all the objects inside it.

First import the copy module, then use copy.deepcopy():

import copy

# Initialize player with a fully independent item collection
player1 = Person("Gimli", 150, 30, 25, copy.deepcopy(party_potions))

3. Handle Copies in the Person Class (Best Practice)

To avoid forgetting to copy every time you create a Person, move the copy logic directly into the Person class's __init__ method:

import copy

class Person:
    def __init__(self, name, hp, mp, atk, items):
        self.name = name
        self.hp = hp
        self.max_hp = hp
        self.mp = mp
        self.max_mp = mp
        self.atk = atk
        # Automatically create a deep copy of items for each person
        self.items = copy.deepcopy(items)

Now every new Person gets their own isolated set of items, no extra work needed when instantiating.

How to Verify It's Fixed

After making these changes, test by modifying one player's items and checking another's:

player1.items.pop(0)  # Remove a potion from player1
print(len(player2.items))  # Should still show 2 potions if the fix works!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:32:54