using % operator to print possibly unitialized data attributes
Leif K-Brooks
eurleif at ecritters.biz
Fri Sep 9 16:08:36 EDT 2005
Adam Monsen wrote:
> class J:
> name = ''
> value = ''
> def __str__(self):
> vals = self.__class__.__dict__
> vals.update(self.__dict__)
> return 'name="%(name)s" value="%(value)s' % vals
This will update the class's attributes with instance attributes when
str() is called, which probably isn't what you want. For instance:
>>> foo = J()
>>> foo.name = "Joe Bloggs"
>>> print foo
name="Joe Bloggs" value="
>>> bar = J()
>>> print bar
name="Joe Bloggs" value="
What's wrong with the obvious version:
class J(object):
name = ''
value = ''
def __str__(self):
return 'name=%r value=%r' % (self.name, self.value)
More information about the Python-list
mailing list