A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2005-September/339690.html below:

using % operator to print possibly unitialized data attributes

using % operator to print possibly unitialized data attributes using % operator to print possibly unitialized data attributesFrançois Pinard pinard at iro.umontreal.ca
Fri Sep 9 18:40:24 EDT 2005
[Adam Monsen]

> The following code uses the % operator to print possibly unitialized
> data attributes:
> ------------------------8<------------------------
> class J:
>     name = ''
>     value = ''
>     def __str__(self):
>         vals = self.__class__.__dict__
>         vals.update(self.__dict__)
>         return 'name="%(name)s" value="%(value)s' % vals

> j = J()
> j.name = "j object"
> print j
> ------------------------>8------------------------

> A couple of questions:
> * is there a simpler or more elegant way to do this?
> * how can I get this to work for new-style classes?

One solution which I used a few times, and which also opens the way to
many other niceties, is to manage so `vals' is a `dict'-like type of
your own.  Then, you write its `__getitem__' method the way you want.

If I remember well, one of the niceties is that whenever `%(EXPR)s'
is used in a format string, EXPR may be a string (well balanced with
regard to parentheses) which you may then choose to "evaluate", for any
definition of "evaluate" which is fruitful for your application. :-)

-- 
François Pinard   http://pinard.progiciels-bpi.ca

More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4