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.