简体   繁体   中英

How to print an object in Python

When I print $ dict of myobject, it return:

{'string': u'abc', 'object': <DEMO.Detail object at 0xb5b691ac>}

I want return an dict of myobject and all object inside my object change to dict too:

{'string': u'abc', 'object': {'obj_string': u'xyz', 'obj_object': {...}}}

Please give me some help about this.

Thanks

If you are the creator of DEMO.Detail , you could add __repr__ and __str__ methods:

class Detail:
    def __str__(self):
        return "string shown to users (on str and print)"
    def __repr__(self):
        return "string shown to developers (at REPL)"

This will cause your object to function this way:

>>> d = Detail()
>>> d
string shown to developers (at REPL)
>>> print(d)
string shown to users (on str and print)

In your case I assume you'll want to call dict(self) inside __str__ .

If you do not control the object, you could setup a recursive printing function that checks whether the object is of a known container type ( list , tuple , dict , set ) and recursively calls iterates through these types, printing all of your custom types as appropriate.

There should be a way to override pprint with a custom PrettyPrinter . I've never done this though.

Lastly, you could also make a custom JSONEncoder that understands your custom types. This wouldn't be a good solution unless you actually need a JSON format.

Could prettyprint do it?

>>> import pprint
>>> a = {'foo':{'bar':'yeah'}}
>>> pprint.pprint(a)
{'foo': {'bar': 'yeah'}}

If your objects have __repr__ implemented, it can also print those.

import pprint
class Cheetah:
    def __repr__(self):
        return "chirp"

zoo = {'cage':{'animal':Cheetah()}}
pprint.pprint(zoo) 

# Output: {'cage': {'animal': chirp}}

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