Pygame卡牌开发疑问:Deck与DeckRep变量为何自动关联?
Hey there! I totally get where you're coming from—this is a super common gotcha in Python when working with mutable objects like lists (which I assume your Deck variable is). Let me break down what's happening and how to fix it:
Why DeckRep is Changing With Deck
When you run DeckRep = Deck at the start of your code, you aren't creating a separate copy of the deck. Instead, you're just making DeckRep point to the exact same object in memory as Deck. So any modifications you make to Deck (like removing cards) will be reflected in DeckRep too—they're just two different names for the same collection of cards.
Even though you only run that assignment once, the link between the two variables stays active because they reference the same object.
How to Fix It
You need to create a shallow or deep copy of Deck instead of just assigning the reference. Here are the best options based on your deck's structure:
1. Shallow Copy (for simple decks)
If your Deck is a list of immutable values (like strings, integers) or you don't need to copy the individual card objects themselves (just the list structure), use one of these:
- Slice notation:
DeckRep = Deck[:] - List's built-in
copy()method:DeckRep = Deck.copy()
2. Deep Copy (for decks with mutable card objects)
If your Deck contains custom mutable Card objects (where you might modify the card's properties later), you'll need a deep copy to fully separate the two decks:
- First import the
copymodule:import copy - Then create the deep copy:
DeckRep = copy.deepcopy(Deck)
Quick Example to Prove It Works
Let's test this with a simple deck of numbers:
# Bad: Reference assignment original_deck = [1, 2, 3, 4, 5] deck_rep = original_deck original_deck.pop() print(original_deck) # Output: [1, 2, 3, 4] print(deck_rep) # Output: [1, 2, 3, 4] (changed too!) # Good: Shallow copy with slice original_deck = [1, 2, 3, 4, 5] deck_rep = original_deck[:] original_deck.pop() print(original_deck) # Output: [1, 2, 3, 4] print(deck_rep) # Output: [1, 2, 3, 4, 5] (stays original!)
Replace your initial DeckRep = Deck line with one of the copy methods above, and DeckRep will stay locked to the original deck state even as you modify Deck.
内容的提问来源于stack exchange,提问作者Alexander Pedersen

