1

I'm trying to create a simple survey by creating a class and creating an instance of it in another file. My problem is that I am getting an error that says my 'question' variable is not defined when I clearly defined it in the start of my program. Here's the error:

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

Here is the class I am instancing:

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)

And here's the code I am working with:

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)

I am running python v.3.5.2

If there are other details you think will be needed, I'll be happy to provide them.

martineau
  • 119,623
  • 25
  • 170
  • 301
jgh
  • 13
  • 2

2 Answers2

2

In that function. question isn't defined. You do, however, have self.question. question is local to the __init__ function.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0
def show_question(self):
    """Show the survey question."""
    print(self.question)

In Python, you have to access class instance attribute with self.

qwerty
  • 116
  • 5