在 Python 中注释函数

心靈之曲
发布: 2024-12-26 15:57:01
原创
347人浏览过

在 python 中注释函数

最近,我撰写了一篇关于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 inner

n = multiplier(6)
n(8) # 48
登录后复制

我们可以创建一个名为number的类型别名,它是int和float的联合类型:

from typing import typealias, Union

number: typealias = Union[int, float]
登录后复制

将参数视为JavaScript数字。

因此,要注释此函数,我们有:

def multiplier(factor: number) -> callable[[number], number]:
    def inner(value: number) -> number:
        return value * factor
    return inner

a = 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 TypeVar

t = TypeVar("t")  # 参数名和变量名必须相同
登录后复制

这样我们就有:

from typing import TypeVar, Sequence

def 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 * 2
print(mymap([1,2,3], twice))
登录后复制

我们可以混合使用callable和TypeVar类型来注释此函数。

from typing import TypeVar, Iterable, Callable

input_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 * 2
print(mymap([1,2,3], twice))
登录后复制

或者我们可以为callable函数创建别名:

from typing import TypeVar, Iterable, Callable

input_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, Callable

input_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<type>{
    stores: type[] = []

    constructor(){
        this.stores = []
    }

    add(item: type){
        this.stores.push(item)
    }
}

const g1 = new genericstore<string>(); //g1.stores: string[]
g1.add("hello") // only strings are allowed
登录后复制

但在Python中,它们相当不同。

  • 首先,我们导入Generic类型,然后让它们成为泛型类的子类。

因此,要在Python中重新创建这个GenericStore类:

from typing import Generic, TypeVar
from dataclasses import dataclass

Type = TypeVar("Type")

@dataclass
class 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 中注释函数的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号