using % operator to print possibly unitialized data attributes

Adam Monsen haircut at
Fri Sep 9 22:30:24 CEST 2005

Leif K-Brooks wrote:
> This will update the class's attributes with instance attributes
> when str() is called, which probably isn't what you want.

Yikes, you're right! Well, I figured out a modification to my original
__str__ code that works for old and new-style classes which doesn't
overwrite the __class__.__dict__:

class J(object):
    name = ''
    value = ''
    def __str__(self):
        vals = dict(self.__class__.__dict__)
        return 'name="%(name)s" value="%(value)s' % vals

> What's wrong with the obvious version:

Oh, that looks nice and clean. I like it.

I also found a recipe in the Python cookbook that works great for
"dumping" objects:
(shortened: )


Adam Monsen

More information about the Python-list mailing list