Mar-06-2020, 03:20 PM
To sort by an attribute, you can use the sorted() built-in function.
As for the code, I have a couple recommendations. You already have a commented out implementation of a better Card so I would get rid of the first one and the setter methods. You'll see why in a moment. Also, instead of Card.identify_card(), make use of the __str__() and __repr__() dunder methods (this is more advanced, but the implementation is easy and you can learn something new!). These methods work with the print() function to provide a custom output for each instance.
As for the code, I have a couple recommendations. You already have a commented out implementation of a better Card so I would get rid of the first one and the setter methods. You'll see why in a moment. Also, instead of Card.identify_card(), make use of the __str__() and __repr__() dunder methods (this is more advanced, but the implementation is easy and you can learn something new!). These methods work with the print() function to provide a custom output for each instance.
class Card: def __init__(self, suit, value): self.value = value self.suit = suit def getvalue(self): return(self.value) def getsuit(self): return(self.suit) def __str__(self): return self.getvalue() + " of " + self.getsuit() def __repr__(self): return self.__str__()With those changes, we can make an improvement to Deck.initialize_deck(). First, give it the same treatment with Deck.__init__() to pass in the suits and values - this makes the Deck more versatile. Then, use a list comprehension (again, more advanced) to make the cards. List comprehensions are faster than loops and more pythonic. Then, add method calls to Deck.initialize_deck() and Deck.shuffle_deck() to Deck.__init__() so it's ready for dealing as soon as it's initialized.
import random from Card import Card class Deck: def __init__(self, suits, values): self.deck_of_cards=[] self.suits = suits self.values = values self.initialize_deck() self.shuffle_deck() def initialize_deck(self): self.deck_of_cards = [Card(s, v) for s in suits for v in values] def shuffle_deck(self): random.shuffle(self.deck_of_cards) def draw_card(self): return self.deck_of_cards.pop() def load_card(self, temp_card): self.deck_of_cards.append(temp_card)