Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Noah Fields
13,985 PointsTwo Quiz.questions lists merging together - how to stop it?
I wrote the following code myself for the Dates and Times in Python course, before watching the video "The Quiz Class". I made some minor edits while watching, as I saw some ways to complete the program that were better than how I'd programmed it myself. I should also note that I customized my code to have a variable number of questions - see the following:
class Quiz:
questions = []
answers = []
def __init__(self, num_of_questions):
question_types = (Add, Multiply)
for _ in range (num_of_questions):
self.questions.append(random.choice(question_types)(random.randint(1,10), random.randint(1,10)))
While I was messing around and testing my code, I entered the following into the console:
import quiz
ab = quiz.Quiz(5)
for x in ab.questions:
print(x.text)
4 + 2
6 * 4
10 * 10
3 + 4
2 * 7
So far, this is correct. However, I then made another quiz instance...
ac = quiz.Quiz(5)
for x in ac.questions:
print(x.text)
4 + 2
6 * 4
10 * 10
3 + 4
2 * 7
6 + 4
4 * 7
7 + 6
3 + 9
6 * 6
Repeating the "for x in ab.questions" code as directly above, which is ab and ac seemingly merged together. I have a vague familiarity with Assembly code (which deals directly with memory in a way Python does not), which was enough to give me at least a general idea of what is happening here. As far as I can tell, ab.questions and ac.questions are taking up adjacent slots in memory, and the processor can't tell where ab ends and ac starts. As such I end up with some amalgamation of the two. Were I writing this in Assembly I could do an alignment, use a filler variable, or something else of that nature - here in Python, however, I have no idea how to fix this problem. Does anyone have a suggestion?
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsThe class attribute questions is not unique across instances ab and ac. The append in the __init__
If, instead, the __init__ initializes self.questions = [] before the append, it will becomes a local variable in each instance.