调用时局部变量引用错误class

Local variable referenced error when calling class

最初我有 2 个文件,一个名为“cards”,一个名为“decks”。卡片文件包含卡片的定义 class 并被导入到“decks”文件中。在甲板文件中是甲板对象的定义。在定义了 deck 对象之后,我将通过键入类似“deck = deck()”的内容在下面的行中测试 class,一切都会正常。

验证完所有内容后,我想将牌组定义移动到“cards”文件中,以创建一个包含“card”和“deck”class 定义的库。然而在这样做之后,运行ning "deck = deck()" 失败了,给出了以下错误。即使我 运行 卡片文件底部的“deck = deck()”行,或者如果我在单独的文件中导入卡片 运行,也会发生这种情况。

"card = card(name = name_of_card,suit = card_suit,value = 0) UnboundLocalError: local variable 'card' referenced before assignment"

下面是卡片文件代码:

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()

您为 class card 和为它创建的对象使用相同的名称。如果您使用不同的名称,您的代码将起作用。通常 classes 的名字以大写字母开头,所以我建议 class Card 然后是 card = Card(name=name_of_card,suit=card_suit,value = 0).