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

后端 未结 5 1597
说谎
说谎 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:33

    Dan's solution is just wrong, and Ismail's in incomplete.

    1. __str__() is not called, __repr__() is called.
    2. __repr__() should return a string, as pformat does.
    3. print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.

    Here is an example

    class S:
        def __repr__(self):
            from pprint import pformat
            return pformat(vars(self), indent=4, width=1)
    
    a = S()
    a.b = 'bee'
    a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
    a.d = S()
    a.d.more_c = a.c
    
    print(a)
    

    This prints

    {   'b': 'bee',
        'c': {   'cats': [   'blacky',
                             'tiger'],
                 'dogs': [   'rex',
                             'king']},
        'd': {   'more_c': {   'cats': [   'blacky',
                                   'tiger'],
                      'dogs': [   'rex',
                                  'king']}}}
    

    Which is not perfect, but passable.

提交回复
热议问题