0

I wanted to understand why the output is returning an error for a certain class of object defined in the code for __str__ command. The Type Error is generated when the __str__ is used with print vis-a-vis return command

class Card():

    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        print (f'{self.rank} of {self.suit}')

The subsequent commands are as follows -

test_card = Card ('Hearts',"Three")
print (test_card)

The output prints as follows -

Three of Hearts
--------------------------------------------------------------------------- TypeError
                                 Traceback (most recent call last) <ipython-input-55-483c6e59f50e> in <module>
      1 test_card = Card ('Hearts',"Three")
----> 2 print (test_card)

TypeError: __str__ returned non-string (type NoneType)
-------------------------------------------------------------------------------

If I change the __str__ function to return f'{self.rank} of {self.suit}' , the output is simply Three of Hearts.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

3

The error message is telling you exactly what is wrong, and you have already found the fix -- the magic __str__ function is supposed to return the string, not print the string and return None.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 2
    I think this question has been [addressed enough](https://stackoverflow.com/questions/linked/750136)... – jonrsharpe Apr 23 '20 at 15:27
  • Posting a link to another answer that I found quite useful especially for novices like myself (3 weeks into learning Python with no prior programming experience) https://stackoverflow.com/a/15441904/13218820 – Nilotpal Choudhury Apr 23 '20 at 15:44