在python中附加对象的copys

时间:2018-03-31 14:52:33

标签: python python-3.x

我正试图在玩家的手中对牌“卡片”进行排序,并创建一个新的“牌”列表,其中只包含那些黑桃牌:

class Card(object):

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

class Player(object):

    def __init__(self, hand):
        self.hand = hand # hand is a list of 13 card objects

    def spades(self):
        spades = []
        for card in self.hand:
            if card.suit == 'spade':
                spades.append(copy.deepcopy(card))
        return spades

但是,调用spades()方法会输出手牌中最后一张牌的相同数量和值的牌列表,以及黑桃数量的相同长度。例如:

players = deal()

for card in players[1].hand:
    print(str(card.value) + ' of ' + card.suit)

print("SPADES")

spades = players[1].spades()

for cards in spades:
     print(str(card.value) + 'of' + card.suit)

输出:

6ofclub
13ofheart
4ofdiamond
7ofspade
13ofdiamond
13ofclub
11ofspade
8ofdiamond
3ofdiamond
10ofheart
8ofheart
12ofclub
12ofdiamond

SPADES
12ofdiamond
12ofdiamond

我认为列表“黑桃”会附加指向变量“card”的指针,而不是新对象。但是我认为使用复制或深层复制可以解决这个问题。

2 个答案:

答案 0 :(得分:1)

从我看到的,代码中没有问题。问题在于最后的印刷品......

您已写过:

for cards in spades:
     print(str(card.value) + 'of' + card.suit)

因此,您正在循环并获取cards但是您正在打印来自前一个for循环的card,该循环仍然是从最后一个循环中分配的变量'最后一次迭代

以下是重现修复的完整代码:

import copy


class Card(object):
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit

    def __str__(self):
        return str(self.value) + " of " + str(self.suit)

class Player(object):
    def __init__(self, hand):
        self.hand = hand # hand is a list of 13 card objects

    def spades(self):
        spades = []
        for card in self.hand:
            if card.suit == 'spade':
                spades.append(copy.deepcopy(card))
        return spades

vals = [i.split("of", 1) for i in """6ofclub
13ofheart
4ofdiamond
7ofspade
13ofdiamond
13ofclub
11ofspade
8ofdiamond
3ofdiamond
10ofheart
8ofheart
12ofclub
12ofdiamond""".strip().split()]

hand = [Card(i[0], i[1]) for i in vals]


players = [None, Player(hand)]

for card in players[1].hand:
    print(card)

print()
spades = players[1].spades()

print("SPADES")
for cards in spades:
     print(cards)  # <----- Print card*s* not card.

答案 1 :(得分:0)

通过更改spades()方法找到解决方案但不完全确定它的工作原理:

def spades(self):
    spades = []
    for card in self.hand:
        if card.suit == 'spade':
            copy = deepcopy(card)
            spades.append(copy)
    return spades

我首先将深拷贝分配给变量,然后通过append()传递变量。这对我来说似乎是一个微不足道的改变......如果有人对这种行为有解释,那将非常感激。