Python 如何指定输入类型函数
要编写可维护的代码,最好按以下方式指定输入和输出类型Python 如何指定输入类型函数,python,python-3.x,Python,Python 3.x,要编写可维护的代码,最好按以下方式指定输入和输出类型 def hash_a(item: object, x: int, y: int) -> int: return x + y 我的问题是如何将函数类型指定为输入类型?比如, def hash_a(funct: object, x: int, y: int) -> int: """ funct : is a fuction """ return x + y 您可以按如下方式使用: from typing i
def hash_a(item: object, x: int, y: int) -> int:
return x + y
我的问题是如何将函数类型指定为输入类型?比如,
def hash_a(funct: object, x: int, y: int) -> int:
"""
funct : is a fuction
"""
return x + y
您可以按如下方式使用:
from typing import Callable
def hash_a(funct: Callable, x: int, y: int) -> int:
...
def hash_a(funct: Callable[[<arg_type_1>, <arg_type_2>, ..., <arg_type_n>], <output_type>], x: int, y: int) -> int:
...
如果希望更精确并指定输入/输出类型,可以使用Callable
作为泛型类型,如下所示:
from typing import Callable
def hash_a(funct: Callable, x: int, y: int) -> int:
...
def hash_a(funct: Callable[[<arg_type_1>, <arg_type_2>, ..., <arg_type_n>], <output_type>], x: int, y: int) -> int:
...
def hash_a(functt:Callable[[,…,],],x:int,y:int)->int:
...
当
时,
和
代表您的可调用用户的签名
如果只关心输出类型,则可以将省略号指定为输入类型:
def hash_a(funct: Callable[..., <output_type>], x: int, y: int) -> int:
...
def hash_a(funct:Callable[…,],x:int,y:int)->int:
...
使用键入。可调用[[int],int]
,其中第一个[int]
是参数的类型,第二个int
是函数的返回类型。可能重复的