Python Newbie

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 24 12:44:58 EST 2013


On Sun, 24 Feb 2013 07:46:07 -0800, piterrr.dolinski 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___________________


To demonstrate that the person who wrote this code was not a good Python 
programmer. I hope it wasn't you :-) This person obviously had a very 
basic, and confused, understanding of Python.

And, quite frankly, was probably not a very good programmer of *any* 
language:

- poor use of Hungarian notation for variable names;
- pointless pre-declaration of values;
- redundant comments that don't explain anything.

If that code came from the code-base you are maintaining, no wonder you 
don't think much of Python! That looks like something I would expect to 
see at the DailyWTF.

http://thedailywtf.com/


The above code is better written as:

x = 32
x_asString = str(x)


Double-underscore methods are used for operator overloading and 
customizing certain operations, e.g. __add__ overloads the + operator. 
You might define a class with a __str__ method to customize converting 
the object to a string:

# Toy example.
class MyObject:
    def __str__(self):
        return "This is my object"


But you would not call the __str__ method directly. (I won't say "never", 
because there are rare, advanced, uses for calling double-underscore 
methods directly.) You would use a public interface, such as the str() 
function.


-- 
Steven



More information about the Python-list mailing list