最近,我撰写了一篇关于TypeScript函数注释的博文。 深入研究后,我了解了更多关于Python函数注释的知识。 本文将使用与上一篇博文类似的示例,讲解Python函数的注释方法。
您可以通过将python.analysis.typecheckingMode设置为basic、standard或strict来验证Visual Studio Code中的类型注释。 basic和standard选项不一定能保证您对函数和变量的注释正确性,但strict模式可以。
函数作为值
您可以在Python中返回函数,并将函数作为值传递。回调函数实际上使用callable类型进行注释,其语法如下:
callable[[argtype1, argtype2, argtype3], returntype]
登录后复制
例如,函数length(text: str) -> int将被注释为callable[[str], int]。
立即学习“Python免费学习笔记(深入)”;
例如,JavaScript中的这个函数:
function multiplier(factor){ return value => factor * value}const n = multiplier(6)n(8) // 48
登录后复制
在Python中可以这样写:
def multiplier(factor): def inner(value): return value * factor return innern = multiplier(6)n(8) # 48
登录后复制
我们可以创建一个名为number的类型别名,它是int和float的联合类型:
from typing import typealias, Unionnumber: typealias = Union[int, float]
登录后复制
将参数视为JavaScript数字。
因此,要注释此函数,我们有:
def multiplier(factor: number) -> callable[[number], number]: def inner(value: number) -> number: return value * factor return innera = multiplier(4.5)a(3) # 13.5
登录后复制
泛型函数
经典的泛型函数示例是:
def pick(array, index): return array[index]pick([1,2,3], 2) # 3
登录后复制
使用TypeVar,我们可以创建更详细的泛型信息(比TypeScript更详细)。
from typing import TypeVart = TypeVar("t") # 参数名和变量名必须相同
登录后复制
这样我们就有:
from typing import TypeVar, Sequencedef pick(array: Sequence[t], index: int) -> t: return array[index]print(pick([1,2,3,4], 2))
登录后复制
那么自定义mymap函数呢?它的作用类似于JavaScript中的map函数。
注意: Python中的map()返回的是迭代器,而不是列表。
def mymap(array, fn): return map(fn, array)def twice(n): return n * 2print(mymap([1,2,3], twice))
登录后复制
我们可以混合使用callable和TypeVar类型来注释此函数。
from typing import TypeVar, Iterable, Callableinput_type = TypeVar("input_type")output_type = TypeVar("output_type")def mymap(array: Iterable[input_type], fn: Callable[[input_type], output_type]) -> Iterable[output_type]: return map(fn, array)def twice(n: int) -> int: return n * 2print(mymap([1,2,3], twice))
登录后复制
或者我们可以为callable函数创建别名:
from typing import TypeVar, Iterable, Callableinput_type = TypeVar("input_type")output_type = TypeVar("output_type")MappableFunction = Callable[[input_type], output_type]def mymap(array: Iterable[input_type], fn: MappableFunction) -> Iterable[output_type]: return map(fn, array)
登录后复制
MappableFunction接受泛型类型输入和输出,并将它们应用到Callable[[input_type], output_type]上下文中。
思考一下myfilter函数该如何注释?
如果您想到了这个:
from typing import Iterable, TypeVar, Callableinput_type = TypeVar("input_type")def myfilter(array: Iterable[input_type], fn: Callable[[input_type], bool]) -> Iterable[input_type]: return filter(fn, array)
登录后复制
您答对了!
泛型类
Python中的泛型类与TypeScript中的定义方式有所不同。
在TypeScript中,您可以这样定义:
class genericstore{ stores: type[] = [] constructor(){ this.stores = [] } add(item: type){ this.stores.push(item) }}const g1 = new genericstore(); //g1.stores: string[]g1.add("hello") // only strings are allowed
登录后复制
但在Python中,它们相当不同。
首先,我们导入Generic类型,然后让它们成为泛型类的子类。
因此,要在Python中重新创建这个GenericStore类:
from typing import Generic, TypeVarfrom dataclasses import dataclassType = TypeVar("Type")@dataclassclass GenericStore(Generic[Type]): store: list[Type] = [] def add(self, item: Type) -> None: self.store.append(item)g1 = GenericStore([True, False]) # g1.store: list[bool]g1.add(False) # only bool is allowed
登录后复制
为什么要学习Python函数注释?
函数注释有助于构建更强大的类型系统,从而减少错误的可能性(尤其是在使用mypy等静态类型检查器时)。此外,当使用强大的类型系统编写库(或SDK)时,可以显著提高使用该库的开发人员的工作效率(主要是因为编辑器的代码提示)。
如果您有任何疑问或发现本文中的错误,请随时在评论区留言。
以上就是在 Python 中注释函数的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2174507.html