搜索
首页后端开发Python教程在 Python 中注释函数

Annotating Functions in 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]

例如;

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 的 TypeAlias,它是 int 和 float 的联合(字面意思),例如;

from typing import TypeAlias, Union

number: TypeAlias = Union[int, float]

将参数视为JavaScript 数字.

因此,要注释这个函数,我们有;

def multiplier(factor: number) -> Callable[[number], number]:
    def inner(value: number) -> inner:
        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") # the argument and the name of the variable should be the same

这样我们就有

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 中的地图。这样我们就有了;

记住:Python中的map()返回的是Iterable类型而不是List类型

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 = TypeVar("Input")  # Input and "Input" must be the same
Output = TypeVar("Output")

def myMap(array: Iterable[Input], fn: Callable[[Input], Output]) -> Iterable[Output]:
    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 = TypeVar("Input")
Output = TypeVar("Output")

MappableFunction = Callable[[Input], Output]

def myMap(array: Iterable[Input], fn: MappableFunction[Input, Output]) -> Iterable[Output]:
    return map(fn, array)

观察 MappableFunction 接受这些泛型类型输入和输出并将它们应用到 Callable[[Input], Output] 的上下文中。

花点时间想想 myFilter 函数将如何注释?

好吧,如果你想到了这个

from typing import Iterable, TypeVar, Callable

Input = TypeVar("Input")

def myFilter(array: Iterable[Input], fn: Callable[[Input], bool]) -> Iterable[Input]:
    return filter(fn, array)

你说得对

通用类

我知道我不应该谈论类注释,但请给我一些时间来解释泛型类。

如果您来自Typescript诗句,这就是您定义它们的方式

class GenericStore<type>{
    stores: Array<type> = []

    constructor(){
        this.stores = []
    }

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

const g1 = new GenericStore<string>(); //g1.stores: Array<string>
g1.add("Hello") //only string are allowed
</string></string></type></type>

但在 Python 中它们却相当不同且尴尬。

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

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

Callable[[argtype1, argtype2, argtype3], returnType]

为什么我应该学习如何在 Python 中注释函数?

正如我在上一篇博客中所说,它有助于构建更智能的类型系统,从而减少出现错误的机会(特别是在使用 mypy 等静态文件检查器时)。此外,当使用强大的类型系统编写库(或 SDK)时,可以大幅提高使用该库的开发人员的工作效率(主要是因为编辑器的建议

如果您有任何疑问或者本文中存在错误,请随时在下面的评论中分享⭐

以上是在 Python 中注释函数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
python中两个列表的串联替代方案是什么?python中两个列表的串联替代方案是什么?May 09, 2025 am 12:16 AM

可以使用多种方法在Python中连接两个列表:1.使用 操作符,简单但在大列表中效率低;2.使用extend方法,效率高但会修改原列表;3.使用 =操作符,兼具效率和可读性;4.使用itertools.chain函数,内存效率高但需额外导入;5.使用列表解析,优雅但可能过于复杂。选择方法应根据代码上下文和需求。

Python:合并两个列表的有效方法Python:合并两个列表的有效方法May 09, 2025 am 12:15 AM

有多种方法可以合并Python列表:1.使用 操作符,简单但对大列表不内存高效;2.使用extend方法,内存高效但会修改原列表;3.使用itertools.chain,适用于大数据集;4.使用*操作符,一行代码合并小到中型列表;5.使用numpy.concatenate,适用于大数据集和性能要求高的场景;6.使用append方法,适用于小列表但效率低。选择方法时需考虑列表大小和应用场景。

编译的与解释的语言:优点和缺点编译的与解释的语言:优点和缺点May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:对于循环,最完整的指南Python:对于循环,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循环用于遍历可迭代对象,while循环用于条件满足时重复执行操作。1)for循环示例:遍历列表并打印元素。2)while循环示例:猜数字游戏,直到猜对为止。掌握循环原理和优化技巧可提高代码效率和可靠性。

python concatenate列表到一个字符串中python concatenate列表到一个字符串中May 09, 2025 am 12:02 AM

要将列表连接成字符串,Python中使用join()方法是最佳选择。1)使用join()方法将列表元素连接成字符串,如''.join(my_list)。2)对于包含数字的列表,先用map(str,numbers)转换为字符串再连接。3)可以使用生成器表达式进行复杂格式化,如','.join(f'({fruit})'forfruitinfruits)。4)处理混合数据类型时,使用map(str,mixed_list)确保所有元素可转换为字符串。5)对于大型列表,使用''.join(large_li

Python的混合方法:编译和解释合并Python的混合方法:编译和解释合并May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

了解python的' for”和' then”循环之间的差异了解python的' for”和' then”循环之间的差异May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串联列表与重复Python串联列表与重复May 08, 2025 am 12:09 AM

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境