使用用户定义的类键入提示 [英] Type hints with user defined classes

查看:43
本文介绍了使用用户定义的类键入提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法找到明确的答案.我想为一个函数做一个类型提示,类型是我定义的某个自定义类,称为 CustomClass().

然后让我们说在某个函数中,将其命名为 FuncA(arg),我有一个名为 arg 的参数.键入提示 FuncA 的正确方法是:

def FuncA(arg: CustomClass):

或者是:

def FuncA(Arg:Type[CustomClass]):

解决方案

前者是正确的,如果arg接受CustomClass<的实例/code>:

def FuncA(arg: CustomClass):# ^ CustomClass 的实例

如果你想要 class CustomClass 本身(或子类型),那么你应该写:

from typing import Type # 你必须导入 Typedef FuncA(arg: Type[CustomClass]):# ^ CustomClass(类对象)本身

就像在关于打字的文档中写的一样强>:

<块引用>

class typing.Type(Generic[CT_co])

C 注释的变量可以接受C 类型的值.在相比之下,用 Type[C] 注释的变量 可以接受以下值是类本身 - 具体来说,它将接受C 的对象.

文档包含一个带有 int 类的示例:

<块引用>

a = 3 # 类型为'int'b = int # 类型为 'Type[int]'c = type(a) # 也有类型 'Type[int]'

Couldn't seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass().

And then let's say in some function, call it FuncA(arg), I have one argument named arg. Would the correct way to type hint FuncA be:

def FuncA(arg: CustomClass):

Or would it be:

def FuncA(Arg:Type[CustomClass]):

解决方案

The former is correct, if arg accepts an instance of CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

In case you want the class CustomClass itself (or a subtype), then you should write:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

Like it is written in the documentation about Typing:

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves - specifically, it will accept the class object of C.

The documentation includes an example with the int class:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

这篇关于使用用户定义的类键入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆