Python 使用用户定义的类键入提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44664040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:20:25  来源:igfitidea点击:

Type hints with user defined classes

pythonpython-3.xuser-defined-typestype-hinting

提问by hhprogram

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().

似乎找不到确切的答案。我想为一个函数做一个类型提示,类型是我定义的一些自定义类,称为它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 FuncAbe:

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

def FuncA(arg: CustomClass):

def FuncA(arg: CustomClass):

Or would it be:

或者它会是:

def FuncA(Arg:Type[CustomClass]):?

def FuncA(Arg:Type[CustomClass]):?

回答by Willem Van Onsem

The former is correct, if argaccepts an instance of CustomClass:

前者是正确的,如果arg接受一个实例CustomClass

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

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

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

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:

就像它写在关于Typing的文档中一样:

class typing.Type(Generic[CT_co])

A variable annotated with Cmay 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.

class typing.Type(Generic[CT_co])

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

The documentation includes an example with the intclass:

该文档包括一个int类示例:

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