All of the python I know, is entirely self taught, but my goal is to of course try to learn what is best practice/ common convention and try to understand why.
I've only recently dug more into OOP, so in efforts to practice OOP, I wrote a blackjack game as I've heard that's a decent quick project to learn a lot of OOP concepts.
The full program can be found here(GitHub): my blackjack game if needed for context (vs just posting the entirety here)
but I'm struggling to understand exactly what super()__init()
does, and if its preferable compared to how I used subclasses: for simplicity take just the following two: Deck
and MultiDeck
which is a subclass of Deck
The following is a snipet from the game:
import collections
import random
import time
Card = collections.namedtuple('Card', ['value', 'suit'])
class Deck:
values = [str(v) for v in range(2, 11)] + list('JQKA')
suits = "Spades Diamonds Hearts Clubs".split()
suit_symbols = ['♠','♦','♥','♣']
def __init__(self):
self.cards = [Card(value, suit) for suit in self.suits for value in self.values]
def __repr__(self):
deck_cards = "Deck()\n"
for card in self.cards:
deck_cards += f"({card.value}-{card.suit})"
return deck_cards
def __len__(self):
return len(self.cards)
def __getitem__(self, position):
return self.cards[position]
def shuffle(self):
random.shuffle(self.cards)
def draw_card(self):
return self.cards.pop()
def reset(self):
self.cards = [Card(value, suit) for suit in self.suits for value in self.values]
class MultiDeck(Deck):
def __init__(self, num_decks):
Deck.__init__(self)
self.values = Deck.values * num_decks
# reshuffle when deck is < 50% length
def is_shuffle_time(self, num_decks):
return len(self) < (len(MultiDeck(num_decks))/2)
def shuffle_time(self):
print("Reshuffling the Deck...\n")
time.sleep(1)
print("Reshuffling the Deck...\n")
time.sleep(1)
print("Reshuffling the Deck...\n")
time.sleep(1)
self.reset()
self.shuffle()
Contrast that to Below: which would be the better way: for one, should super() be declared in the superclass Deck
or left out? I've stumbled upon a lot of seemingly different answers (but its possible that might be a result of python 3 compared to older versions)
Is it better to instead define MultiDeck
like:
class MultiDeck(Deck):
def __init__(self, num_decks):
super().__init__()
self.values = super().values * num_decks
and on that last line, in initializing self.values
is it better to use Deck.values
or super().values
If using super() is in fact better practice, what advantage or added benefit does super().__init()
provide. and is writing it like Deck.__init__(self)
more frowned upon (if so, why?)
I hope I even used it correctly, for example purposes...from what I've read that seemed to be the way to use super(), but please correct me if not.
Thank you for any input in advance.