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:
>>
>> 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
>>
>> 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 [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
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)?
Michael
More information about the Python-list
mailing list