pprinting objects
Martin Blume
mblume at socha.net
Sat Dec 8 06:48:22 EST 2007
"Donn Ingle" schrieb
> Is there a way to get a dump of the insides of an object?
> I thought pprint would do it.
>
print would actually like to do it if you told it how to do it.
print actually does it, but takes a default implementation if
you do not override __repr__ or __str__.
> If I had a class like this:
>
> class t:
> def __init__(self):
> self.x=1
> self.y=2
> self.obj = SomeOtherObj()
>
> Then it could display it as:
>
> <class> t,
> x,1,
> y,2,
> obj,<class SomeOtherObj>
>
> Or something like that -- a complete output of the object really,
> with id()'s and so forth.
>
Define a __repr__ or __str__ method for the class:
class t:
def __init__(self):
self.x=1
self.y=2
self.obj = SomeOtherObj()
def __repr__(self):
s = "<class> %s\n x,%d\n y,%d\n obj,<class %s>" \
% (self.__class__, self.x, self.y, self.obj.__class__)
return s
a_t = t()
print "a t obj: %s" % (a_t)
a t obj: <class> __main__.t
x,1
y,2
obj,<class __main__.SomeOtherObj>
HTH
Martin
More information about the Python-list
mailing list