0

I used class to help in creating a list called students:

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

    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major


def make_student(name, age, major):
    return Student(name, age, major)`

To print from the list, this is what I thought would produce the desired result . . .

# First Method
for i in students:
    print i

but this was the output:

<__main__.Student object at 0x108770710>
<__main__.Student object at 0x108770790>
<__main__.Student object at 0x1087707d0>`

So I used:

# Second Method
for i in students:
    print i.name, i.age, i.major

and here was the output I had been hoping for:

John 21 Maths
Mary 22 Philosophy
Georgina 25 Biology

My question is why the first method doesn't result in the second methods's output, and is there a way to get the second method's output without specifying each of the individual attributes?

New Alexandria
  • 6,951
  • 4
  • 57
  • 77
Jeptha
  • 65
  • 8
  • yes there is. I will link to duplicate. Show us how your class Student look like. – Anton vBR Feb 18 '18 at 17:18
  • Thank you @AntonvBR – Jeptha Feb 18 '18 at 17:39
  • Why would you expect your first method to work like your second method? Simply put, it's behavior is not defined to work that way. – juanpa.arrivillaga Feb 18 '18 at 18:32
  • My expectation is naive, and I suspect Python is not actually creating a list somewhere the way I think it is. My naive thinking is that there is actually a list of students with their attributes somewhere and that each could be produced by its handle, but the first method result shows I am wrong. – Jeptha Feb 18 '18 at 18:49

0 Answers0