小编Gom*_* A.的帖子

如何注释类型实例(而不是类实例)?

注释需要类对象而不是该类实例的函数参数的正确方法是什么?

在下面的例子中,some_class参数应该是一个类型实例(它是一个类),但这里的问题type太宽泛了:

def construct(some_class: type, related_data:Dict[str, Any]) -> Any:
    ...
Run Code Online (Sandbox Code Playgroud)

some_class需要特定类型对象的情况下,使用type根本没有帮助.该typing模块可能需要一个Class泛型来执行此操作:

def construct(some_class: Class[Union[Foo, Bar, Baz]], related_data:Dict[str, Any]) -> Union[Foo, Bar, Baz]:
    ...
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,some_classFoo,BarFaz类,而不是它的一个实例.它们在类树中的位置无关紧要,因为它some_class: Class[Foo]也应该是一个有效的案例.因此,

# classes are callable, so it is OK
inst = some_class(**related_data)
Run Code Online (Sandbox Code Playgroud)

要么

# instances does not have __name__
clsname = some_class.__name__
Run Code Online (Sandbox Code Playgroud)

要么

# an operation that only Foo, Bar and Baz can perform.
some_class.a_common_classmethod()
Run Code Online (Sandbox Code Playgroud)

应该是mypy,pytype,PyCharm等等. …

python annotations type-hinting

9
推荐指数
1
解决办法
2340
查看次数

标签 统计

annotations ×1

python ×1

type-hinting ×1