简体   繁体   中英

Why does print expect __str__ to return str?

Print has no problem printing a dict:

d = dict()
d['x'] = 'y'
print(d)

{'x': 'y'}

Then why does this fail?

class Utterance:
    def __init__(self, intent_name, text):
        self.intent_name = intent_name
        self.text = text

    def __str__(self):
        return dict(self.__dict__)

print(utterance)
 Traceback (most recent call last): print(utterance) TypeError: __str__ returned non-string (type dict)

(I know it is standard for __str__ to return string, but I have a reason related to JSON encoding to return dict)

From documentation :

object.__str__(self)
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

tl;dr
Why does print expect str to return str?

Because language spec says so.

object.__str__ is meant to return a human readable string representation of your object, in your case, this method returns a dict , you may use:

class Utterance:
    def __init__(self, intent_name, text):
        self.intent_name = intent_name
        self.text = text

    def __str__(self):
        return self.__dict__.__str__()

print(Utterance(1, 'my_text'))

output:

{'intent_name': 1, 'text': 'my_text'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM