Python:如何定义一个行为类似函数的类?

AGu*_*oux 3 python class function

我想在 python 中定义一个类,其行为类似于具有附加属性的函数。特别是,它应该无缝地应用于变量。

\n

让\xe2\x80\x99s尝试用数学例子来解释。假设我非常喜欢 sinino\xc3\xafdal 函数,但也对它们的频率感兴趣。函数 x -> sin(omega x) 具有属性频率,即 omega 的值。它也可以应用于浮点数 x。

\n

我可以写:

\n
from numpy import sin, pi\n\nclass SinFunc:\n    def __init__(self, omega):\n        self.frequency = omega\n\n    def apply_to(self, x):\n        return sin(self.frequency * x)\n
Run Code Online (Sandbox Code Playgroud)\n

然后我可以使用 sinino\xc3\xafdal 函数:

\n
MySinFunc = SinFunc(3)\nprint(MySinFunc.frequency)\nprint(MySinFunc.apply_to(pi)) \n# output\n# 3\n# 0 (almost!)\n
Run Code Online (Sandbox Code Playgroud)\n

但我想要的是能够直接写入MySinFunc(pi),并且属性频率仍然定义。

\n

如何实现?\n谢谢!

\n

gsh*_*hka 9

要使对象可调用,您需要添加一个__call__处理调用的类方法。

将您的apply_to函数重命名为__call__,它将起作用。