I am currently implementing a class that can handle numeric data associated with physical units.
I would like to implement a way of calculating the square root of an instance. Assume that you have an instance of a class that has attributes value and name:
from math import sqrt
class Foo:
def __init__(self, value, name)
self.value = value
self.name = name
def __sqrt__(self):
return sqrt(self.value)
I would like to implement a function similar to the magic methods like add(self, other) that would calculate the squareroot when I call the math.sqrt() function:
A = Foo(4, "meter")
root = math.sqrt(A)
should return call the A.sqrt() function.
You can't without reassigning math.sqrt
to a custom function. If you want to allow Foo
to be cast to int
or float
you can implement __int__
and __float__
and cast before calling math.sqrt
:
class Foo:
def __init__(self, value, name)
self.value = value
self.name = name
def __float__(self):
return float(self.value)
def __int__(self):
return int(self.value)
A = Foo(4, "meter")
root = math.sqrt(float(A))
EDIT: According to the comments below, it seems that you can invoke math.sqrt(A)
directly if Foo
implements __float__
due to how the math module is implemented. I would still rather be explicit than implicit.