1

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")
1
  • Have you ever done this: a = str(obj); print(a)? Or this: print("my object:", obj)? Try your print implementation on those examples and it should be obvious why you wouldn't do that. Commented Aug 27, 2014 at 4:46

2 Answers 2

5

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)
>>> 
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure if "casting" is the right word, but +1.
Thanks, conversion seems to be the more correct terminology.
2

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.