Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Outputting Specific Prosperities of an Array(List) of Objects in Python

I have an class Student which has an array(list) of Objects called Students. I am trying to output the names of all the students in the array.

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

Students = []

Students.append(Student("Dave",23,"Chem"))
Students.append(Student("Emma",34,"Maths"))
Students.append(Student("Alex",19,"Art"))

print(Students[0].__dict__)
print(Students[1].__dict__)
print (Students[0])

Both the ways I have found and tired do not output the specific name but the location or the whole object. Is there a way to just output the name? For example output Students[0] name Dave

{'name': 'Emma', 'age': 34, 'major': 'Maths'}
<__main__.Student object at 0x000001FCDE4C2FD0>```

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you just want the name, you can print(Students[0].name). If you want to see the relevant attributes when printing a Student object, you can implement the __repr__ method.

class Student:

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def __repr__(self):
        return f"<Student name={self.name} age={self.age} major={self.major}>"

This way you can simply do print(Students[0]) to see the name, age and major of a student.

By the way, for a normal class definition, you want to initialize instance attributes inside the __init__ method, instead of declaring them above __init__: those are class attributes. Please read this section of the documentation to familiarize yourself with the syntax.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading