Trebek / pydealer

A simple package containing classes/methods for constructing decks of playing cards (standard 'French deck'). Could be used for a CLI game, or even a graphical game as well.
http://pydealer.rtfd.org
GNU General Public License v3.0
78 stars 19 forks source link

add __str__, __repr__, __hash__, and __eq__ to Card class #5

Closed gfairchild closed 10 years ago

gfairchild commented 10 years ago

I saw this project /r/python, and it looks really solid. Got a small recommendation: add __str__, __repr__, __hash__, and __eq__ to the Card class. This will allow me to do this:

c = Card('Ace', 'Spades')
print(c)
c2 = Card('Ace', 'Diamonds')
print(c == c2)

I suggest something like this:

def __str__(self):
    return '%s' % (self.name)

def __repr__(self):
    return 'Card(value=%r, suit=%r)' % (self.value, self.suit)

def __hash__(self):
    return hash((self.value, self.suit))

def __eq__(self, other):
    return isinstance(other, Card) and self.value == other.value and self.suit == other.suit

I'm a big fan of implementing these 4 methods for base classes like Card because then I can use them in data structures (set, dict, etc.) without having to worry about unexpected behavior. I can also print a card and print card-related errors and get meaningful information.

Trebek commented 10 years ago

Good ideas! Will do this.

Trebek commented 10 years ago

Added those magic methods, and a few more to both Card and Deck, in the dev branch.