Python Forum

Full Version: def __str__(self) gives error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, the function def __str__(self) while I put inside the class is giving indent error. But if put outside doesn't give output.

plz advice.
Use code tags
The def __str__ method most be inside the Student class.
Then you just print(s1) to get output from __str__
class Student:
     def __init__(self,name, roll_no):
         self.name = name
         self.roll_no = roll_no

     def __str__(self):
         return f"{self.name} has roll number {self.roll_no}."
       
s1 = Student("Arjun", 1)
print(s1)  
s1.name = "Dhananjay"
print(s1)  
Output:
Arjun has roll number 1. Dhananjay has roll number 1.