Home > Net >  'dict' object has no such attribution error - basic python
'dict' object has no such attribution error - basic python

Time:11-04

I have created a function under a class, and trying to call that function on a read txt file. More specifically, Loop over the "student objects" and call the "print_myself" method on each of them. the output of the row iteration looks ok, but when I try calling the function on the output of the row iteration, it gives me an attribution error - and I can't seem to fix it myself.

I attached the class, function code as well, could anyone please help me out? Thank you

class Student:
    def __int__(self,firstname,lastname,status,gpa):
        self.firstname = firstname 
        self.lastname = lastname
        self.status = status
        self.gpa = gpa
    def print_myself(self):
        print("First Name:\t{}".format(self.firstname))
        print("Last Name:\t{}".format(self.lastname))
        print("Status:\t{}".format(self.status))
        print("GPA:\t{}".format(self.gpa))

Iterated over the rows of the table and create a student object for each of the data entries, store the student objects on a list "students".

import pandas as pd

students = []
data = pd.read_csv('students.txt')
df = pd.DataFrame(data)
for index, row in df.iterrows():
    students.append({'firstname':row['firstname'],
                     'lastname':row['lastname'],
                     'status':row['status'],
                     'gpa':row['gpa']})

print(students)
Student.print_myself(student)

OUTPUT of print(students)

[{'firstname': 'Mike', 'lastname': 'Barnes', 'status': 'freshman', 'gpa': 4.0}, {'firstname': 'Jim',....

ERROR : no attribute (for Student.print_myself(students))

AttributeError: 'dict' object has no attribute 'firstname'

CodePudding user response:

I see two problems: print_myself is an instance method, so you need an instance of the class like Student().

That is, instead of:

Student.print_myself(student)

I'd suggest:

students[0].print_myself()

The second is when adding to students, in the line students.append, you're appending a dict object, but it should be first converted to a Student object.

So for example, this line:

students.append({'firstname':row['firstname'],
                     'lastname':row['lastname'],
                     'status':row['status'],
                     'gpa':row['gpa']})

I'd suggest trying it like:

students.append(Student(**row))

Or, to be safer:

students.append(Student(**{'firstname':row['firstname'],
                           'lastname':row['lastname'],
                           'status':row['status'],
                           'gpa':row['gpa']}))

CodePudding user response:

You haven't instantiated a new object of class Student

  • Related