class game_type(object):
def __init__(self):
select_game = raw_input("Do you want to start the game? ")
if select_game.lower() == "yes":
player1_title = raw_input("What is Player 1's title? ").lower().title()
class dice_roll(object,game_type):
current_turn = 1
current_player = [player1_title,player2_title]
def __init__(self):
while game_won == False and p1_playing == True and p2_playing == True:
if raw_input("Type 'Roll' to start your turn %s" %current_player[current_turn]).lower() == "roll":
我一直收到一条错误,内容如下: NameError:名称'player1_title'未定义
我理解标题是一个函数,所以我尝试使用player1_name和player1_unam,但这些也返回了相同的错误:(
有人可以帮忙吗
非常感谢所有答案
答案 0 :(得分:5)
导致NameError的内容很多。
首先,game_type的__init__
方法不保存任何数据。要分配实例变量,您必须使用self.
指定类实例。如果不这样做,那么您只需分配局部变量。
其次,如果要在子类中创建一个新的函数并且仍然需要父类的效果,则必须使用__init__
显式调用父类的super()
函数。
基本上,你的代码应该是
# Class names should be CapCamelCase
class Game(object):
def __init__(self):
select_game = raw_input("Do you want to start the game? ")
if select_game.lower() == "yes":
self.player1_title = raw_input("What is Player 1's title? ").lower().title()
# Maybe you wanted this in DiceRoll?
self.player2_title = raw_input("What is Player 1's title? ").lower().title()
# If Game were a subclass of something, there would be no need to
# Declare DiceRoll a subclass of it as well
class DiceRoll(Game):
def __init__(self):
super(DiceRoll, self).__init__(self)
game_won = False
p1_playing = p2_playing = True
current_turn = 1
current_players = [self.player1_title, self.player2_title]
while game_won == False and p1_playing == True and p2_playing == True:
if raw_input("Type 'Roll' to start your turn %s" % current_players[current_turn]).lower() == "roll":
pass