Python Forum
def __str__(self) gives error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
def __str__(self) gives error
#1
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.

Attached Files

.py   class_py_student.py (Size: 525 bytes / Downloads: 59)
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: __str__ returned non-string (type tuple) Anldra12 1 8,780 Apr-13-2021, 07:50 AM
Last Post: Anldra12
  TypeError: __str__ returned non-string error jolinchewjb 5 11,722 Jan-24-2019, 07:54 AM
Last Post: jolinchewjb
  Magic method __str__ dan789 16 10,746 Dec-23-2018, 03:59 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020