why i love python...

Mark McEahern mark at mceahern.com
Thu Feb 7 02:34:52 CET 2002


[please forgive the embedded html; this is posted on my weblog, but since
that's not exclusively about python, i didn't want to bore you all with it.]

what started out as just an attempt to make debugging easier turned into an
epiphany about why i love python.  allow me to share that love...

python comes with a slew of special methods for objects that you can
leverage to do some really neat things.  consider __str__, which is called
on your objects when you <b>print</b> them.  if you don't define __str__,
that's ok, you'll get something like this:

<pre>
>>>class Simple:pass
...
>>> s = Simple()
>>> print s
<__main__.Simple instance at 0x100fd4c8>
</pre>

by defining __str__, i get to control the output generated by print (and
str()):

<pre>
>>> class Prints:
...     def __str__(self):
...             return "whatever i like"
...
>>> p = Prints()
>>> print p
whatever i like
</pre>

obviously, i should return something more meaningful than that.  for
instance, it might be nice to return an xml representation of the object.
again, with python this is unbelievably easy:

<pre>
>>> class PrintsXml:
...     def __str__(self):
...             s = "<%s>" % self.__class__.__name__
...             for key in self.__dict__:
...                     s += "<%s>%s</%s>" % (key, self.__dict__[key], key)
...             s += "</%s>" % self.__class__.__name__
...             return s
...
>>> p = PrintsXml()
>>> p.name = "foo"
>>> p.type = "bar"
>>> print p
<PrintsXml><type>bar</type><name>foo</name></PrintsXml>
</pre>

this snippet shows:

<ul>
  <li>how you can use self.__dict__ to access an object's attributes.</li>
  <li>how you can iterate over the keys of a dictionary (i believe that's
new with python 2.2).</li>
  <li>how you can use self.__class__ to access an instance's class; and
__class__.__name__ to access the name of the class as a string.</li>
</ul>

side note:  i'm doing all this in the interactive interpreter.  just fire up
python and start typing.  i like that.

i think this shows some of the power of python.  particularly, how special
methods can save you an amazing amount of time.  to me, the natural next
step for this code is to make PrintsXml a virtual base class and beef up its
handling of complex attributes, particularly:

<ul>
  <li>handle list attributes intelligently.</li>
  <li>determine whether attributes are themselves subclasses of PrintsXml,
in which case you can just let them print themselves rather than wrapping
them in xml tags manually.</li>
</ul>

of course, i haven't even touched on the most exciting aspect of all this:
__repr__.  __repr__ allows me to return a string representation of my object
that can be used to re-create it.  what i don't know is how that compares to
pickling, but i'm sure the latter is tastier.  ;-)

cheers,

// mark





More information about the Python-list mailing list