-1

I've seen the term __str__ used a lot within classes in Python. I've tried to look up what it means and its functions but many websites teach it in relation to the Java function toString or __repr__. As I don't come from a Java background, its hard for me to learn it that way. I've also seen people compare it to the function str() but I don't know how accurate that is or in what ways.

Could someone explain it to me in simple terms? Thanks.

  • Are you asking about `__str__` in general or about the difference between `__str__` and `__repr__`? – finefoot Dec 30 '19 at 21:43

2 Answers2

1

When Python needs to convert a class instance to a string, it calls its __str__() method. If it doesn't have __str__() it falls back on __repr__(). If the class doesn't define either of these methods, it will normally inherit them from the object base class, which returns a string like <className object at 0x1234>

This is used by the str() function, as well as formatting methods like str.format(), the string % operator, and f-strings. So defining the __str__() method allows you to customize how objects in your class are displayed in messages.

Analogously, the repr() function calls the __repr__() method. This method is generally intended to return a string containing a representation more appropriate for debugging and/or parsing, rather than for end user display.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The __str__ magic method defines the string representation of an object.

Here is an example for a very boring class A:

>>> class A:
...     pass
... 
>>> str(A())
'<__main__.A object at 0x7fe249b93ac8>'

This is the default. It uses the built-in __str__ method inherited from object. For our class B, we're looking for a more individual approach:

>>> class B:
...     def __str__(self):
...         return "Something individual"
... 
>>> str(B())
'Something individual'

If you're looking for the difference between __str__ and __repr__, have a look here Difference between __str__ and __repr__?

finefoot
  • 9,914
  • 7
  • 59
  • 102