我创建了一个名为Dog_card
的类。这样,我创建了player_card
和computer_card
。我正在尝试比较这两个对象的相同属性。每个值都比friendliness
多,但是我删除了它们,因此更易于测试。我不断收到错误消息:
NameError: name 'player_card' is not defined
这是我的代码:
class Dog_card:
def __init__(self):
self.name = ""
self.friendliness = ""
def printing_card(self):
prnt_str = "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
return prnt_str
def printing_player_card():
player_card = Dog_card()
player_card.name = dogs_list_player[0]
player_card.friendliness = random.randint(1,101)
def printing_computer_card():
computer_card = Dog_card()
computer_card.name = dogs_list_computer[0]
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")
任何帮助将不胜感激
答案 0 :(得分:0)
问题出在错误中。基本上,当player_card
的定义内未定义choose_category()
时,您将尝试使用它。我建议您将player_card
的值传递给如下函数
def choose_category(player_card):
或者您可以将其定义为属性,以便同一类的方法可以访问它。
答案 1 :(得分:0)
您需要在使用play_card之前对其进行初始化。也许您是为了进行初始化而调用printing_player_card的,但是由于您没有从该函数返回任何内容,因此创建的对象和变量player_card仅在该函数的范围内。该函数完成后,player_card对象变量未知,该对象被破坏。
如果您希望player_card(以及computer_card)支持其功能,则需要将其返回并保存到功能代码之外的变量中。
此外,您的函数名称“ printing”不好,因为您什么都不打印。您只需初始化对象即可。
也许这就是您的目标。
class Dog_card:
def __init__(self, name, friendliness=1):
self.name = name
self.friendliness = friendliness
def __str__(self):
return "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
player_card = Dog_card(dogs_list_player[0], random.randint(1,101))
computer_card = Dog_card(dogs_list_copmuter[0])
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")