Printing results of creating a class

Not getting the results of the student printed,please help

Thanks

you do? I can clearly see it:

<__main__.Student object at address>

not what you expected?

I was expecting it to print the name,age,career and university of stu_1 that is

Jagmeet
21
Accounting
University of Strathmore

that is not the default behavior of the class representation, but you can change this using a magic method:

python - How to create a custom string representation for a class object? - Stack Overflow

I corrected it I printed


print(stu_1.name)
print(stu_1.career)


etc for each item

Thanks

Using a string representation, you’ll easily be able to differentiate your objects from one another.
Let’s have your Student object printed using a string representation. For this, you’ll need to define a repr function inside the class definition:-

def __repr__(self):
        return "{}, {}, {}, {}".format(self.name, self.age, self.career, self.university)

in this case, you’ll get a printed string wherever you print out an object.

Stu_1 = Student("Jagmeet", 21, "Accounting", "University of Strathmore")
print(Stu_1)

#will print out

Jagmeet, 21, Accounting, University of Strathmore

Hope that helps!

1 Like