简体   繁体   English

如何将类对象追加到列表

[英]How to append class object to list

After instantiating a deck ( deck = Deck() ), calling deck.show_deck() just prints out "two of diamonds" 52 times. 实例化一个牌组( deck = Deck() )后,调用deck.show_deck()只会打印出“两颗钻石” 52次。 The 'copy' part is as per this answer , but doesn't seem to help. “复制”部分根据此答案 ,但似乎无济于事。 Any suggestions? 有什么建议么?

import copy
from card import Card

class Deck:

    card_ranks = ['ace','king','queen','jack','ten','nine','eight','seven','six','five','four','three','two']
    card_suites = ['clubs','hearts','spades','diamonds']

    deck = []   

    def __init__(self):
        #create a deck of 52 cards

        for suite in Deck.card_suites:
            for rank in Deck.card_ranks:
                Deck.deck.append(copy.deepcopy(Card(card_rank=rank, card_suite=suite)))



    def show_deck(self):
        for item in Deck.deck:
            print item.get_name()

Card: 卡:

class Card:

    card_name = ''

    def __init__(self, card_rank, card_suite):
        self.card_rank = card_rank.lower()
        self.card_suite = card_suite.lower()
        Card.card_name = card_rank + " of " + card_suite

    def get_name(self):
        return Card.card_name

The problem here is that the Card class has a name variable which is shared with all instances of the Card class. 这里的问题是, Card类有与的所有实例共享一个名字变量Card类。

When you have: 当你有:

class Card:

    card_name = ''

This means that all Card objects will have the same name ( card_name ) which is almost surely not what you want. 这意味着所有Card对象将具有相同的名称( card_name ),这几乎肯定不是您想要的名称。

You have to make the name be part of the instance instead like so: 您必须像这样将名称设为实例的一部分:

class Card:
    def __init__(self, card_rank, card_suite):
        self.card_rank = card_rank.lower()
        self.card_suite = card_suite.lower()
        self.card_name = card_rank + " of " + card_suite

    def get_name(self):
        return self.card_name

You will find that the deepcopy is not needed, nor was it ever needed, but it does show you that deepcopy will not allow you to keep different states of class variables. 您会发现既不需要也不需要deepcopy ,但是它确实向您显示了deepcopy将不允许您保留类变量的不同状态。

Further I would recommend you change Card to have it's own __str__ method if you want to print it out: 此外,如果要打印出来,我建议您更改Card使其具有自己的__str__方法:

class Card:
    def __init__(self, card_rank, card_suite):
        self.card_rank = card_rank.lower()
        self.card_suite = card_suite.lower()

    def __str__(self):
        return "{0} of {1}".format(card_rank, card_suit)

This uses the Python language itself to print the class and has the upside that your class will now work properly in print statements and in conversions to strings. 这使用Python语言本身来打印类,并且具有这样的好处,即您的类现在可以在打印语句和字符串转换中正常工作。 So instead of: 所以代替:

print some_card.get_name()

you could do 你可以做

print some_card

To expand on what shuttle87 said: 进一步讲一下Shuttle87所说的内容:

class Card:

    card_name = ''

makes card_name a static variable (shared between all instances of that class) 使card_name成为静态变量(在该类的所有实例之间共享)

Once you make the variable non-static (by using self.card_name in the __init__ method) you won't have to worry about the copy part as each instance of the card class will have it's own unique name 一旦使变量成为非静态变量(通过在__init__方法中使用self.card_name ),您就不必担心复制部分,因为card类的每个实例将具有其自己的唯一名称。

On that note, the deck in Deck is also static in your code. 值得注意的是, deck中的平台在代码中也是静态的。

from card import Card

class Deck:
    # these 2 can be static, they never change between copies of the deck class
    card_ranks = ['ace','king','queen','jack','ten','nine','eight','seven','six','five','four','three','two']
    card_suites = ['clubs','hearts','spades','diamonds']

    def __init__(self):
        # this shouldn't be static since you might want to shuffle them 
        # or do other things that make them unique for each deck
        self.cards = []

        for suite in Deck.card_suites:
            for rank in Deck.card_ranks:
                self.cards.append(Card(rank, suite))

    def show_deck(self):
        for item in self.cards:
            print item

class Card:
    def __init__(self, rank, suite):
        self.rank = rank
        self.suite = suite

    def __str__(self):
        return self.rank + ' of ' + self.suite

#! python2

from deck import Deck

def main():
    deck = Deck()

    deck.show_deck()

if __name__ == '__main__':
    main()

ace of clubs
king of clubs
queen of clubs
jack of clubs
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM