
最近,我撰写了一篇关于TypeScript函数注释的博文。 深入研究后,我了解了更多关于Python函数注释的知识。 本文将使用与上一篇博文类似的示例,讲解Python函数的注释方法。
您可以通过将python.analysis.typecheckingMode设置为basic、standard或strict来验证Visual Studio Code中的类型注释。 basic和standard选项不一定能保证您对函数和变量的注释正确性,但strict模式可以。
您可以在Python中返回函数,并将函数作为值传递。回调函数实际上使用callable类型进行注释,其语法如下:
<code class="python">callable[[argtype1, argtype2, argtype3], returntype]</code>
例如,函数length(text: str) -> int将被注释为callable[[str], int]。
立即学习“Python免费学习笔记(深入)”;
例如,JavaScript中的这个函数:
<code class="javascript">function multiplier(factor){
return value => factor * value
}
const n = multiplier(6)
n(8) // 48</code>在Python中可以这样写:
<code class="python">def multiplier(factor):
def inner(value):
return value * factor
return inner
n = multiplier(6)
n(8) # 48</code>我们可以创建一个名为number的类型别名,它是int和float的联合类型:
<code class="python">from typing import typealias, Union number: typealias = Union[int, float]</code>
将参数视为JavaScript数字。
因此,要注释此函数,我们有:
<code class="python">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</code>经典的泛型函数示例是:
<code class="python">def pick(array, index):
return array[index]
pick([1,2,3], 2) # 3</code>使用TypeVar,我们可以创建更详细的泛型信息(比TypeScript更详细)。
<code class="python">from typing import TypeVar
t = TypeVar("t") # 参数名和变量名必须相同</code>这样我们就有:
<code class="python">from typing import TypeVar, Sequence
def pick(array: Sequence[t], index: int) -> t:
return array[index]
print(pick([1,2,3,4], 2))</code>那么自定义mymap函数呢?它的作用类似于JavaScript中的map函数。
注意: Python中的map()返回的是迭代器,而不是列表。
<code class="python">def mymap(array, fn):
return map(fn, array)
def twice(n): return n * 2
print(mymap([1,2,3], twice))</code>我们可以混合使用callable和TypeVar类型来注释此函数。
<code class="python">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))</code>或者我们可以为callable函数创建别名:
<code class="python">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)</code>MappableFunction接受泛型类型输入和输出,并将它们应用到Callable[[input_type], output_type]上下文中。
思考一下myfilter函数该如何注释?
如果您想到了这个:
<code class="python">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)</code>您答对了!
Python中的泛型类与TypeScript中的定义方式有所不同。
在TypeScript中,您可以这样定义:
<code class="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</code>但在Python中,它们相当不同。
Generic类型,然后让它们成为泛型类的子类。因此,要在Python中重新创建这个GenericStore类:
<code class="python">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</code>函数注释有助于构建更强大的类型系统,从而减少错误的可能性(尤其是在使用mypy等静态类型检查器时)。此外,当使用强大的类型系统编写库(或SDK)时,可以显著提高使用该库的开发人员的工作效率(主要是因为编辑器的代码提示)。
如果您有任何疑问或发现本文中的错误,请随时在评论区留言。
以上就是在 Python 中注释函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号