Python Newbie

Chris Angelico rosuav at gmail.com
Sun Feb 24 16:52:43 CET 2013


On Mon, Feb 25, 2013 at 2:46 AM,  <piterrr.dolinski at gmail.com> wrote:
> Hi guys,
>
> Question. Have this code
>
> intX = 32                          # decl + init int var
> intX_asString = None               # decl + init with NULL string var
>
> intX_asString = intX.__str__ ()    # convert int to string
>
> What are these ugly underscores for? _________________str___________________

Normally you don't need them. Write it this way:

intX_asString = str(intX)

The "dunder" methods ("d"ouble "under"score, leading and trailing),
also called "magic methods", are the implementations of various
special features. For instance, indexing foo[1] is implemented using
the __getitem__ method. Here's a list:

http://docs.python.org/3.3/reference/datamodel.html#special-method-names

You'll seldom, if ever, call these methods directly.

By the way, when you're asking a completely new question, it usually
helps to do so as a brand new thread (not a reply) and with a new
subject line. Otherwise, you risk people losing the new question among
the discussion of the old.

ChrisA



More information about the Python-list mailing list