Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: intX.__str__() ??

Thread Tools

Re: intX.__str__() ??

Michael Torrie
Posts: n/a
On 02/24/2013 09:23 AM, Ethan Furman wrote:
> On 02/24/2013 07:46 AM, Removed) 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___________________

> This is a good example of why you shouldn't program language X in language Y.
> For starters, `intX.__str__` should be written as `str(intX)`;
> For middlers, intX_asString is probably not necessary (is it being printed? then
> do a `print intX`, or a `print "size left on disk: %d" % intX`, etc.
> For finishers, why the System Hungarian Notation?

I think he's maintaining existing code. It's unfortunate that his first
exposure to python is code written by someone else in such a poor style,
and in a way that definitely isn't pythonic. No wonder he's struggling
to like python! Though I'm sure since his recent experience has been
exclusively in C# that he probably uses hungarian notation as a matter
of course. A hard habit to break! Is this a good time to introduce him
to duck typing? Probably not.

Another way to explain the double underscore methods is that they are
how things like operator overloading is performed. Want to make a class
that you can use the [index] notation on instances? Define the
__get_attr__() method. And to define a class that you can then use
instances with the + operator? Define the __add__() method. This is a
good introduction:
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off