Panos
Panos

Reputation: 1834

How to overload numeric operators in Python

I was recently working with Python and wanted to use another way of finding square roots. For example I wanted to find square root of n with Newton-Raphson approximation. I need to overload the overload the ** (only when you raise a number to 0.5),o perator as well as math.sqrt(), because I have several older projects that could be sped up by doing so and replacing all math.sqrt() and **(0.5) with another function isn't ideal.

Could this be done in Python?

Is it possible to overload either ** or math.sqrt?

Any helpful links are also much appreciated.

def Square_root(n):
    r = n/2
    while(abs(r-(n/r)) > t):
        r = 0.5 * (r + (n/r))
    return r

print(2**(0.5)) ## changes to print(Square_root(2))
print(math.sqrt(2)) ## that also becomes print(Square_root(2))

Upvotes: 0

Views: 2389

Answers (2)

volcano
volcano

Reputation: 3582

If you really want to overload languages int and float objects - you can use variants of magic functions. In order to be consistent, you'll have to write a lot of code.

A lot of work. Python is for lazy people - if you like to write a lot, stick to Java or C++ :)

Upvotes: 1

m0nhawk
m0nhawk

Reputation: 24168

In short: you can't change the behavior of __pow__ for built-in types.

Long answer: you can subclass the float, but it will require additional coding and refactoring of the input values of the program, to the new float class with overwritten operators and functions.

And you can overwrite the math.sqrt, but this is not recommended:

import math
math.sqrt = lambda x, y: print(x, y)
math.sqrt(3, 2)
# 3 2

This will require the custom function to have the same signature.

Upvotes: 1

Related Questions