< Back to Code Samples
# File: survey.py
# The Survey class and related classes
# G. Weber, 2007 Oct 26
from threading import Lock
class Survey (object):
def __init__ (self, name, response_file, questions):
super(Survey, self).__init__()
self.name = name
self.resp_file = response_file
self.question_list = questions
self.lock = Lock()
def get_questions(self):
return self.question_list
def add_response (self, response):
# * * * begin critical section * * *
self.lock.acquire()
file = open(self.resp_file, 'a') # append
for q in self.question_list:
qid = q.id
file.write("%s %s\n" % (qid, response[qid-1]))
file.write('\n')
file.close()
self.lock.release()
# * * * end critical section * * *
class Question (object):
def __init__ (self, id, text, answer_list):
"""id is a unique identifier for the question,
at least unique within this survey.
text is a string: the text of the question.
answer_list is a list of Answers, the possible responses
to the question."""
super(Question, self).__init__()
self.id = id
self.text = text
self.answer_list = answer_list
class Answer (object):
def __init__ (self, label, text):
"""label is a short key that identifies the answer, such as a, b, c.
text is the full text of the answer."""
super(Answer, self).__init__()
self.label = label
self.text = text