English

Explain __str__ with an example.

Advertisements
Advertisements

Question

Explain __str__ with an example.

Code Writing
Explain
Advertisements

Solution

__str__ is a special method that returns the readable string representation of an object. It is called automatically by print(object) or str(object).

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def __str__(self):
        return f"Name: {self.name}, Marks: {self.marks}"


s1 = Student("Aman", 92)
print(s1)

Name: Aman, Marks: 92
shaalaa.com
  Is there an error in this question or solution?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 10. | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×