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
Type hints with user defined classes
提问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 FuncA
be:
然后让我们说在某个函数中,调用它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 arg
accepts an instance of CustomClass
:
该前者是正确的,如果arg
接受一个实例CustomClass
:
def FuncA(arg: CustomClass):
# ^ instance of CustomClass
In case you want the class CustomClass
itself (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
C
may accept a value of typeC
. In contrast, a variable annotated withType[C]
may accept values that are classes themselves- specifically, it will accept the class object ofC
.
class typing.Type(Generic[CT_co])
带有注释的变量
C
可以接受类型为 的值C
。相比之下,用注释Type[C]
的变量可能接受类本身的值- 具体来说,它将接受 的类对象C
。
The documentation includes an example with the int
class:
该文档包括一个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]'