Created
June 28, 2018 14:43
-
-
Save colonelrascals/4752eefe21df5443515ec82f7323364e to your computer and use it in GitHub Desktop.
Data Class example python 3.7 release
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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