Originally I had 2 files, one named "cards" and one named "decks". The cards file contain the definition of the cards class and was imported into the "decks" file. In the decks files was the definition of the deck object. After defining the deck object, I would test the class in the lines below by typing something like "deck = deck()" and everything would work.
After verifying everything, I wanted to move the deck definition into the "cards" file, to create a library that would contain both the "card" and "deck" class definitions. However after doing this, running "deck = deck()" failed, giving the following error. This happens even if I run the "deck = deck()" line in the bottom of the cards file, or if I import cards an run in a separate file.
"card = card(name = name_of_card,suit = card_suit,value = 0) UnboundLocalError: local variable 'card' referenced before assignment"
Below is the cards file code:
import random
class card:
def __init__(self, name, suit, value):
self.name = name
self.suit = suit
self.value = value
class deck:
def __init__(self, contents = [], num_cards = 0):
self.contents = contents
self.num_cards = num_cards
self.generate()
def generate(self):
card_values = ['Ace', *range(2,11,1),'Jack', 'Queen', 'King']
suits = ['Hearts','Clubs','Diamonds','Spades']
for i in suits:
card_suit = str(i)
for n in card_values:
name_of_card = str(n) + " of " + card_suit
card = card(name = name_of_card,suit = card_suit,value = 0)
self.contents.append(card)
self.num_cards += 1
def shuffle(self):
random.shuffle(self.contents)
def print_contents(self):
for i in self.contents:
print(i.name)
def draw_card(self):
card_drawn = self.contents[0]
self.contents.pop(0)
return card_drawn
def reveal(self,num_to_reveal = 1,from_top = True):
for i in range(0,num_to_reveal,1):
if from_top == True:
print(self.contents[i].name)
else:
print(self.contents[-1-i].name)
def return_to_deck(self,card, position = 0):
self.contents.insert(position,card)
deck = deck()
You're using the same name for the class
card
and for the object you create for it. Your code will work if you use different names. Typically classes have names starting with a capitol letter, so I'd suggestclass Card
and then later,card = Card(name=name_of_card,suit=card_suit,value = 0)
.