Tor*_*lla 5 python magic-methods
我目前正在实现一个可以处理与物理单位相关的数字数据的类。
我想实现一种计算实例平方根的方法。假设您有一个具有属性值和名称的类实例:
from math import sqrt
class Foo:
def __init__(self, value, name)
self.value = value
self.name = name
def __sqrt__(self):
return sqrt(self.value)
Run Code Online (Sandbox Code Playgroud)
我想实现一个类似于add (self, other) 等魔术方法的函数,当我调用 math.sqrt() 函数时,它会计算平方根:
A = Foo(4, "meter")
root = math.sqrt(A)
Run Code Online (Sandbox Code Playgroud)
应该返回调用A.sqrt ( )函数。
math.sqrt如果不重新分配给自定义函数,您就无法做到这一点。如果您想允许Foo强制转换为int,或者您可以在调用之前float实现__int__and和强制转换:__float__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))
Run Code Online (Sandbox Code Playgroud)
编辑:根据下面的评论,由于数学模块的实现方式,您似乎可以math.sqrt(A)直接调用 if FooImplements 。__float__我还是宁愿直白而不是含蓄。