question on log as an instance method

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Oct 7 06:04:15 EDT 2012


On Sun, 07 Oct 2012 10:33:36 +0200, Franck Ditter wrote:


> Question : I may consider + as an hidden instance method , as 1+2 is
> equivalent to (1).__add__(2) ? I also consider __abs__ as an instance
> method :
>>>> (-2).__abs__()
> 2

The short answer is, yes.

The *correct* answer is, not quite.

So-called "dunder" methods (Double leading and trailing UNDERscore) 
methods like __add__, __abs__, __len__ and many others are treated 
slightly differently from ordinary instance methods, but only when they 
are automatically invoked by Python.

If you explicitly call `instance.__add__(value)`, __add__ is treated as 
an ordinary instance method. But when you call `instance + value`, Python 
automatically invokes the __add__ method, but using slightly different 
method resolution rules. This is done for the sake of speed.


> Question 1 : could the parser cope with the mandatory space in 1
> .__add__(2) ?

Why not try it and see?

py> 1 .__add__(2)
3

 
> Question 2 : After importing math, why can't I consider log as an
> instance method, after all ?
>>>> (4).__log__()
> AttributeError: 'float' object has no attribute '__log__'


Because importing a module does not magically add new methods to classes.

Floats do not have a __log__ method, because they don't need one. 
Importing math doesn't create such a method. Why would it? What is the 
purpose of __log__? math.log doesn't need it.


-- 
Steven



More information about the Python-list mailing list