I’m learning python (with VBA background) by building a black-jack game (Yes, I’ve asked a bunch of questions using blackjack as an example).
Here’s my code:
import random
class DECK():
def load_deck(self):
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
full_deck = {}
i = 0
for s in suite:
for r in rank:
full_deck[i] = "%s of %s" % (r, s)
i += 1
return full_deck
def pick_item(self, deck):
card_key = random.choice(deck.keys())
new_card = deck[card_key]
del deck[card_key]
return (deck, new_card)
def missing_card(self, deck):
temp_deck = DECK()
print temp_deck
d1 = DECK()
deck1 = d1.load_deck()
deck1, card1 = d1.pick_item(deck1)
print card1
d1.missing_card(d1)
Here’s what I get in the terminal (file namehand_c.py):
$ python hand_c.py
Ace of Clubs
<__main__.DECK instance at 0x10bb0d248>
$
Why does one function work pick_item, but not the other missing_card?
Per the first answer, I changed the function definition to:
def missing_card(self, deck):
deckC1 = DECK()
temp_deck = deckC1.load_deck
print temp_deck
But now I get the following from the terminal:
$ python hand_c.py
Jack of Diamonds
<bound method DECK.load_deck of <__main__.DECK instance at 0x10500e248>>
$
I modified your program to work. I introduced a constructor and changed the representation of your deck to a list instead of a dictionary, and made it to a instance variable that belongs to the deck you create in the line
d1 = DECK(). Every method in your class now has access to your deck, without revealing your internal representation of the deck to the world and you only have to work with the one DECK object.