How to use pprint to print an object using the built-in __str__(self) method?

后端 未结 5 1681
说谎
说谎 2021-02-13 16:44

I have a Python script which processes a .txt file which contains report usage information. I\'d like to find a way to cleanly print the attributes of an object using pprint\'s

5条回答
  •  半阙折子戏
    2021-02-13 17:25

    pprint is just another form of print. When you say pprint(vars(self)) it prints vars into stdout and returns none because it is a void function. So when you cast it to a string it turns None (returned by pprint) into a string which is then printed from the initial print statement. I would suggest changing your print to pprint or redefine print as print if its all you use it for.

    def __str__(self):
        from pprint import pprint
        return str(vars(self))
    
    for i,line in enumerate(open(path+file_1,'r')):
        line = line.strip().split("|")
        if i == 0:
            headers = line
        if i == 1:
            record = Report(line,headers)
            pprint record
    

    One alternative is to use a formatted output:

    def __str__(self):
        return "date added:   %s\nPrice:        %s\nReport:       %s\nretail price: %s\nuser:         %s" % tuple([str(i) for i in vars(self).values()])
    

    Hope this helped

提交回复
热议问题