Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

Can anyone tell me, How to print the instances of a class utilizing the print()?

1 Answer

0 votes
by (26.4k points)

Kindly check the below code:

>>> class Test:

...     def __repr__(self):

...         return "Test()"

...     def __str__(self):

...         return "member of Test"

... 

>>> t = Test()

>>> t

Test()

>>> print(t)

member of Test

Here,

  • The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

  • If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

Related questions

0 votes
1 answer
asked Jul 6, 2019 in Python by Sammy (47.6k points)
+2 votes
2 answers
+1 vote
2 answers
0 votes
1 answer
0 votes
2 answers

Browse Categories

...