Reputation: 3483
I wonder why the python magic method (str) always looking for the return statement rather a print method ?
class test:
def __init__(self):
print("constructor called")
def __call__(self):
print("callable")
def __str__(self):
return "string method"
obj=test() ## print constructor called
obj() ### print callable
print(obj) ## print string method
my question is why i can't use something like this inside the str method
def __str__(self):
print("string method")
Upvotes: 1
Views: 303
Reputation: 18908
This is more to enable the conversion of an object into a str
- your users don't necessary want all that stuff be printed into the terminal whenever they want to do something like
text = str(obj_instance)
They want text
to contain the result, not printed out onto the terminal.
Doing it your way, the code would effectively be this
text = print(obj_instance)
Which is kind of nonsensical because the result of print isn't typically useful and text
won't contain the stream of text that was passed into str
type.
As you already commented (but since deleted), not providing the correct type for the return value will cause an exception to be raised, for example:
>>> class C(object):
... def __str__(self):
... return None
...
>>> str(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type NoneType)
>>>
Upvotes: 5
Reputation: 53525
Because __str__()
is used when you print
the object, so the user is already calling print
which needs the String that represent the Object - as a variable to pass back to the user's print
In the example you provided above, if __str__
would print you would get:
print(obj)
translated into:
print(print("string method"))
Upvotes: 2