In [1]:
class Card:
"""Represents a standard playing card."""
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Queen', 'King']
def __str__(self):
return "{} of {}".format(Card.rank_names[self.rank],
Card.suit_names[self.suit])
def __eq__(self, other):
return self.suit == other.suit and self.rank == other.rank
def __lt__(self, other): # <
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return t1 < t2
In [2]:
import random
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def pop_card(self):
return self.cards.pop()
def add_card(self, card):
self.cards.append(card)
def shuffle(self):
random.shuffle(self.cards)
def sort(self):
self.cards.sort()
def move_cards(self, hand, num):
for i in range(num):
hand.add_card(self.pop_card())
In [3]:
class Hand(Deck):
"""Represents a hand of playing cards."""
def __init__(self, label=''):
self.cards = []
self.label = label
In [4]:
hand = Hand("new hand")
d = Deck()
d.shuffle()
d.move_cards(hand, 5)
print(hand)
hand.sort()
print()
print(hand)
In [5]:
def find_defining_class(obj, meth_name):
for ty in type(obj).mro(): # method resolution order
if meth_name in ty.__dict__:
return ty
In [6]:
print(find_defining_class(hand, 'shuffle'))