Problem with creating a new instance

This is the place for queries that don't fit in any of the other categories.

Problem with creating a new instance

Postby avcdent » Thu Oct 03, 2013 3:32 pm

I define a class name 'student' and use it as value in a Dictionary, here is my code below:

studentclass.py
Code: Select all
class Student:
    def __init__(self,ass1,ass2,exam):       
        self._ass1=ass1
        self._ass2=ass2
        self._exam=exam
 
    def get_info(self,temp):       
        return self._ass1,self._ass2,self._exam

democlass.py
Code: Select all
import studentclass
def main():
    student={}
    cont='y'
    while cont=='y' or cont=='Y':
        ID=input('Enter the student ID: ')
        ass1=input('Enter the assignment 1 grade: ')
        ass2=input('Enter the assignment 2 grade: ')
        exam=input('Enter the final exam grade: ')
        mark=studentclass.Student(ass1,ass2,exam)
        student[ID]=mark
        cont=input('Do you want to add more student: ')
       
    print('Results')
    for i in student:       
        _ass1,_ass2,_exam=mark.get_info(i)
        print(i,'\t',_ass1,'\t',_ass2,'\t',_exam)
       
main()

Here is the test data and results
Code: Select all
Enter the student ID: 001
Enter the assignment 1 grade: 1
Enter the assignment 2 grade: 2
Enter the final exam grade: 3
Do you want to add more student: y
Enter the student ID: 002
Enter the assignment 1 grade: 4
Enter the assignment 2 grade: 5
Enter the final exam grade: 6
Do you want to add more student: n
Results
002     4     5     6
001     4     5     6


As you see, the grades of Student 002 replace all the grades of Student 001. Does anyone tell me what's happen.
Thanks a lot.
Last edited by Yoriz on Thu Oct 03, 2013 5:08 pm, edited 1 time in total.
Reason: First post lock, Added code tags
avcdent
 
Posts: 2
Joined: Thu Oct 03, 2013 3:17 pm

Re: Problem with creating a new instance

Postby Yoriz » Thu Oct 03, 2013 5:09 pm

Hi, welcome to the forum.
Please read the 'new user read this' link in my signature.
I've added code tags to your code for you, please ensure you use them when posting code to maintain the indentation.

You are not getting the student from the dictionary, you are just using the last created student.
Code: Select all
_ass1,_ass2,_exam=mark.get_info(i)

Would need to be
Code: Select all
_ass1,_ass2,_exam=student[i].get_info(i)
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 836
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Problem with creating a new instance

Postby avcdent » Fri Oct 04, 2013 11:24 am

Thank you for helping me ^^!!
avcdent
 
Posts: 2
Joined: Thu Oct 03, 2013 3:17 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], metulburr and 6 guests