What are the differences between the __str__() and str() methods in python?
- 16,580
- 17
- 88
- 94
- 11
-
check this https://docs.python.org/3/reference/datamodel.html. Look for __str__ – akshat Apr 26 '18 at 04:22
-
In some sense, `str == operator.methodcaller('__str__')` defines the relationship between the two. – chepner Apr 26 '18 at 04:42
-
1@Jerrybibo Not quite. `str` is a *type*; `__str__` is an *instance* method. – chepner Apr 26 '18 at 04:45
-
good point. @chepner I need to brush up on my terminologies. – Jerrybibo Apr 26 '18 at 04:49
2 Answers
__str__ (usually read dunder, for double under) is an instance method that is called whenever you run str(<object>) and returns the string representation of the object.
str(foo) acts as a function trying to convert foo into a string.
Note:
There is also a __repr__() method which is fairly similar to __str__(), the main difference being __repr__ should return an unambiguous string and __str__ is for a readable string. For a great response on the diffences between the two I'd suggest giving this answer a read.
- 43
- 4
- 1,005
- 8
- 19
__str__() is a magic instance method that doee this: when you print a class instance variable with print(), it will give you a string that can be modified by changing the returned string in the __str__() method. There's probably a better explanation to it but I can show you with code:
class Thing:
def __init__(self):
pass
def __str__(self):
return "What do you want?" #always use return
a = Thing()
print(a)
OUTPUT:
What do you want?
str() just converts a variable into a string type variable.
print(str(12.0))
OUTPUT:
'12.0'
You can confirm it is a string using the type() function.
print(type(str(12.)))
I don't know the exact output of that but it will peobably have 'str' in it.