user6852136
user6852136

Reputation:

List not printing in python

I'm writing a code to understand inheritance and here is what I did so far.

class Master:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.full_name = first_name + last_name
        self.email_id = (first_name + last_name + '@vit.com').lower()

class Student(Master):

    def __init__(self, first_name, last_name, reg_num):
        super().__init__(first_name, last_name)
        self.reg_num = reg_num

    def __str__(self):
        return self.first_name + " " + self.last_name

class Proctor(Master):

    def __init__(self, first_name, last_name, students=None):
        super().__init__(first_name, last_name)
        if students is None:
            self.students = []
        else:
            self.students = students


stud_1 = Student('kishan', 'B', '16BEI0067')
proctor_1 = Proctor('Mani', 'Mozhi', [stud_1])

print(proctor_1.students)

When the last print statement excutes, instead of getting the details of stud_1, I get [<__main__.student object at 0x7f362206a908>]

What is going wrong?

Upvotes: 0

Views: 2565

Answers (3)

JoshG
JoshG

Reputation: 6745

There are a number of ways that you could print the attributes of an object in Python. Here's one other way. This will print the attributes of the object:

for attr in dir(proctor_1):
    if hasattr(proctor_1, attr):
        print("proctor_1.%s = %s" % (attr, getattr(proctor_1, attr)))

You could also wrap this in a dump function and then call dump(obj) to print out the attributes.

Upvotes: 0

henriman
henriman

Reputation: 153

You are printing the object itself, not the attributes. To print those you have to either go through the list with a for loop and call the attributes in this way:

for s in proctor_1.students:
    print(s.first_name, s.last_name)  # and so on

Or you could implement the __str__ dunder method:

def __str__(self):
    return s.first_name + " " + s.last_name

(Or however you want the output to look like.)

Upvotes: 0

Pierre
Pierre

Reputation: 1099

You need to add an __str__() method to your student class to indicate how it should be printed:

class Student(Master):
    def __init__(self, first_name, last_name, reg_num):
        super().__init__(first_name, last_name)
        self.reg_num = reg_num

    def __str__(self):
        return self.first_name + " " + self.last_name

Upvotes: 1

Related Questions