how to overload sqrt in a module?

Robert Kern robert.kern at gmail.com
Fri Mar 3 04:39:05 CET 2006


Michael McNeil Forbes wrote:
> Here is one fairly ugly solution:
> 
> module_g.py
> -----------
> def g(x,math):
>     return math.sqrt(x)
> 
> 
>>>>import math, cmath, module_g
>>>>module_g.g(2,math)
> 
> 1.4142135623730951
> 
>>>>module_g.g(-2,cmath)
> 
> 1.4142135623730951j
> 
> I am sure there is a better way of doing this that makes use of the 
> type of the argument (Dynamical scoping would solve the 
> problem but we don't want to go there...).  Note that the following 
> function would work fine
> 
> def f(x):
>     return abs(x)
> 
> because of the special member __abs__ attached to the type.  There is no 
> corresponding member for sqrt, sin etc.
> 
> What is the "proper" pythonic way to do this?

Use the appropriate library which already implements the features you want.

In [8]: class A(object):
   ...:     def __init__(self, x):
   ...:         self.x = x
   ...:     def sqrt(self):
   ...:         return 2*self.x
   ...:
   ...:

In [9]: a = A(10)

In [10]: import numpy

In [11]: numpy.sqrt(a)
Out[11]: 20

In [12]: numpy.sqrt(10)
Out[12]: 3.1622776601683795

In [13]: numpy.sqrt(10j)
Out[13]: (2.2360679774997898+2.2360679774997898j)

-- 
Robert Kern
robert.kern at gmail.com

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list