how to overload sqrt in a module?
Michael McNeil Forbes
mforbes at lnsDOTmit.edu
Fri Mar 3 06:44:09 CET 2006
> Michael McNeil Forbes wrote:
>> Here is one fairly ugly solution:
>> def g(x,math):
>> return math.sqrt(x)
>>>>> import math, cmath, module_g
>> What is the "proper" pythonic way to do this?
On Thu, 2 Mar 2006, Robert Kern wrote:
> Use the appropriate library which already implements the features you want.
> In : class A(object):
> ...: def __init__(self, x):
> ...: self.x = x
> ...: def sqrt(self):
> ...: return 2*self.x
> In : a = A(10)
> In : import numpy
> In : numpy.sqrt(a)
> Out: 20
> In : numpy.sqrt(10)
> Out: 3.1622776601683795
> In : numpy.sqrt(10j)
> Out: (2.2360679774997898+2.2360679774997898j)
> Robert Kern
Thanks. This solution is essentially to make sure that all "numeric"
objects have .sqrt etc. members, and then use a library which check
against builtin types and custom types with these extensions.
That works, as long as the appropriate library exists (or I write it
myself) (and this works in my case: I did not realize that the numpy/scipy
functions worked this way.)
Are there any other more generic solutions (without having to write
"custom" functions like numpy.sqrt)?
More information about the Python-list