如何在python中命名和创建一个类的多个实例?

时间:2019-02-12 17:44:39

标签: python python-3.x class instance

我是编程和学习OOP的新手。我想创建一副扑克牌,所以我创建了一个名为Card的类,其中包含数字属性和西服属性。然后我想创建该类的52个实例的列表以制作套牌。我也希望每个人都被命名为“ 2_spades”,“ 3_spades”,“ 4_spades”等等,但显然不希望手动进行。

当我使用for循环创建列表并打印列表时,它打印了实例的内存位置,这可以理解,因为我没有命名实例。因此,我尝试将str dunder方法添加到类中,该方法返回了实例的编号和西装。但是没用。

class Card:
    def __init__(self, number, suit, trump='not the trump'):
        self.number = number
        self.suit = suit
        self.trump = trump

    def make_trump(self):
        self.trump = 'the trump'

    def remove_trump(self):
        self.trump = 'not the trump'

    def __str__(self):
        return f'{self.number} of {self.suit}'


suits = ['spades', 'hearts', 'clubs', 'diamonds']
deck = []
for Suit in suits:
    for i in range(13):
        deck.append(Card(i. Suit))

print(deck)

当我打印卡座时,它会为每个卡座提供存储位置。

我如何创建Card类的多个实例,并通过它们的number_suit或self.number_self.suit为其命名?

1 个答案:

答案 0 :(得分:0)

如果您打印list本身的内容list,则使用repr(element)打印它的元素 :

class Card: 
    def __init__(self, number, suit, trump='not the trump'):
        self.number = number
        self.suit = suit
        self.trump = trump

    def make_trump(self):
        self.trump = 'the trump'

    def remove_trump(self):
        self.trump = 'not the trump'

    def __str__(self):
        return f'{self.number} of {self.suit}'

    # provide the __repr__ method to be the same as str so iterables
    # when printing this will not print the memory adress but the more
    # meaningfull representation
    def __repr__(self):
        return str(self)   # same as str

应该可以解决问题

您可以简单地

suits = ['spades', 'hearts', 'clubs', 'diamonds']
deck = []
for Suit in suits:
    for i in range(13):
        deck.append(Card(i, Suit))   # fix this

print(deck)

输出:

[0 of spades, 1 of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 
 6 of spades, 7 of spades, 8 of spades, 9 of spades, 10 of spades, 11 of spades, 
 12 of spades, 0 of hearts, 1 of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 
 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, 
 11 of hearts, 12 of hearts, 0 of clubs, 1 of clubs, 2 of clubs, 3 of clubs, 4 of clubs, 
 5 of clubs, 6 of clubs, 7 of clubs, 8 of clubs, 9 of clubs, 10 of clubs, 11 of clubs, 
 12 of clubs, 0 of diamonds, 1 of diamonds, 2 of diamonds, 3 of diamonds, 4 of diamonds, 
 5 of diamonds, 6 of diamonds, 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, 
 11 of diamonds, 12 of diamonds]