Skip to content

Instantly share code, notes, and snippets.

@colonelrascals
Created June 28, 2018 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colonelrascals/4752eefe21df5443515ec82f7323364e to your computer and use it in GitHub Desktop.
Save colonelrascals/4752eefe21df5443515ec82f7323364e to your computer and use it in GitHub Desktop.
Data Class example python 3.7 release
from dataclass import dataclass, field
from typing import List
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
SUITS = '♣ ♢ ♡ ♠'.split()
def make_french_deck():
return [PlayingCard(r,s) for s in SUITS for r in RANKS]
@dataclass(order=True)
class PlayingCard:
sort_index = int = field(init=False, repr=False)
rank: str
suit: str
def __post_init__(self):
self.sort_index = (RANKS.index(self.rank) * len(SUITS)
+ SUITS.index(self.suit))
def __str__(self):
return f'{self.suit}{self.rank}'
@dataclass
class Deck:
cards: List[PlayingCard] = field(default_factory=make_french_deck)
def __repr__(self):
cards = ', '.join(f'{c!s}' for c in self.cards)
return f'{self.__class__.__name__}({cards})'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment