簡體   English   中英

當我嘗試運行這段代碼時,我不斷收到命名錯誤(Python)

[英]I keep getting a naming error when i try to run this piece of code (Python)

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,但它們也返回了相同的錯誤:(

有人可以幫忙嗎

非常感謝所有答案

導致NameError的原因有很多。

首先,game_type的__init__方法不會保存任何數據。 要分配實例變量,您必須使用self.指定類實例self. 如果不這樣做,那么您只是在分配局部變量。

其次,如果您要在子類中創建新的__init__函數,但仍希望獲得父類的效果,則必須使用super()顯式調用父類的__init__函數。

所以基本上,您的代碼應該是

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM