如何通过函数注释指示函数需要一个函数作为参数,或返回一个函数? [英] How to indicate that a function expects a function as a parameter, or returns a function, via function annotations?
问题描述
你可以在python 3中使用函数注解来指示参数的类型和返回值,像这样:
You can use function annotations in python 3 to indicate the types of the parameters and return value, like so:
def myfunction(name: str, age: int) -> str:
return name + str(age) #usefulfunction
但是如果您正在编写一个函数,它需要一个函数作为参数,或者返回一个函数呢?
But what if you were writing a function that expects a function as a parameter, or returns one?
我意识到您可以为注释编写任何有效的表达式,因此我可以将函数"写为字符串,但这是最好的/唯一的方法吗?有没有像内置类型 int/float/str/list/dict
等?我知道 callable
,但我想知道是否还有其他东西.
I realize that you can write any valid expression in for the annotations, so I could write "function" as a string, but is that the best/only way of doing it? Is there nothing like the built-in types int/float/str/list/dict
etc? I'm aware of callable
, but I'm wondering if there's anything else.
推荐答案
没有为注释定义样式.使用 callable
、types.FunctionType
或字符串.
There's no style defined for annotations. Either use callable
, types.FunctionType
or a string.
PS:callable
在 Python 3.0 和 3.1 中不可用
PS: callable
was not available in Python 3.0 and 3.1
这篇关于如何通过函数注释指示函数需要一个函数作为参数,或返回一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!