2016-12-16 41 views
0

我試圖通過創建一個類並在另一個文件中創建一個實例來創建一個簡單的調查。我的問題是,我收到一個錯誤,說我的'問題'變量沒有定義,當我在我的程序開始時明確定義它。這裏的錯誤:獲取NameError:定義變量時未定義

line 11, in show_question print(question)/
    NameError: name 'question' is not defined 

這裏是我實例化類:

class AnonymousSurvey(): 
    """Collect anonymous answers to a survey question.""" 

    def __init__(self, question): 
     """Store a question, and prepare to store responses.""" 
     self.question = question 
     self.responses = [] 

    def show_question(self): 
     """Show the survey question.""" 
     print(question) 

這裏還有我一起工作的代碼:

from survey import AnonymousSurvey 

# Define a question, and make a survey. 
question = "What language did you first learn to speak?" 
my_survey = AnonymousSurvey(question) 

# Show the question, and store responses to the question. 
my_survey.show_question() 
print("Enter 'q' at any time to quit.\n") 
while True: 
    response = input("Language: ") 
    if response == 'q': 
     break 
    my_survey.store_response(response) 

我正在蟒蛇v.3.5。 2

如果您還有其他需要的細節,我會很樂意爲您提供。

+0

應該通過'self'引用'question',即使用'print(self.question)'。 –

回答

2

在那個函數中。 question未定義。但是,您的確有self.questionquestion是本地的__init__功能。

0
def show_question(self): 
    """Show the survey question.""" 
    print(self.question) 

在Python中,您必須訪問self的類實例屬性。

+2

這是一個實例屬性。不是班級「領域」。 –

+0

@ JimFasarakis-Hilliard耶謝謝。當我寫這篇文章的時候,我想不起來 – qwerty