type批注: 我想在python中实现一个高阶函数,为此,我想使用显式参数类型。有没有办法显示“功能”类型?
def high_order_math(a: Float, b: Float, func: function):
return func(a,b)
这是一些发现,感谢所有分享您的知识的人
def high_order_math(a: float, b: float, func: Callable[[float, float], float]) -> float:
return func(a, b)
high_order_math(1,2,3)
回溯(最近通话最近一次):
文件“”,第
行第1行文件“”,第2行,在high_order_math中
TypeError:“ int”对象不可调用
答案 0 :(得分:7)
使用Callable
中的typing
类型。 Callable
类型是泛型的,因此您可以指定函数的签名。
from typing import Callable
def high_order_math(a: float, b: float, func: Callable[[float, float], float]) -> float:
return func(a, b)
答案 1 :(得分:1)
您收到了很好的答案,但是在函数体内,您可以验证传递的参数是否可调用:
def high_order_math(a: float, b: float, func):
if not callable(func):
raise TypeError
else:
print(a + b)
high_order_math(1, 2, lambda x, y: x + y) # works because it's callable
high_order_math(1, 2, 'hello') # raises error because it's not callable
答案 2 :(得分:0)
尝试一下:
>>> def high_order_math(a, b, func):
... if callable(func):
... return func(a, b)
... raise TypeError(f"{type(func)} is not a function or callable")
...
>>> high_order_math(3, 4, lambda a,b: a+b)
7