-2
class Test:
     def __init__(self,top,bottom):
         self.num = top
         self.den = bottom

     def __str__(self):
         return str(self.num)+"/"+str(self.den)

What is the use of this __str__(self)? why do we use __methodname__() in python? Is there any specific use?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    Method names prefixed and suffixed with a double-underscore are reserved for use by Python, and typically are used as hooks for customizing object behavior. They aren't really private, but they aren't meant to be called explicitly. – chepner Jan 28 '20 at 21:14
  • See the [Descriptive: Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) section of [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) about ' "magic" objects or attributes'. – martineau Jan 28 '20 at 21:22

1 Answers1

1

Some good reading for you:

tl/dr: the functions that start and end with double underscores are special functions which are automatically called as part of class behavior. For example, when an object should be coerced into a string, the __str__() function is called. For an object to support coercion to string, it must implement this function.

Cargo23
  • 3,064
  • 16
  • 25