2021年8月28日 星期六

[ Python 常見問題 ] Type hints with user defined classes

 Source From Here

Question
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:
  1. def FuncA(arg: CustomClass):  
Or would it be:
  1. def FuncA(Arg:Type[CustomClass]):  
HowTo
The former is correct, if arg accepts an instance of CustomClass:
  1. def FuncA(arg: CustomClass):  
  2.     #     ^ instance of CustomClass  
In case you want the class CustomClass itself (or a subtype), then you should write:
  1. from typing import Type  # you have to import Type  
  2.   
  3. def FuncA(arg: Type[CustomClass]):  
  4.     #     ^ CustomClass (class object) itself  
Like it is written in the documentation about Typing:
  1. class typing.Type(Generic[CT_co])  
A variable annotated with 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:
  1. a = 3         # Has type 'int'  
  2. b = int       # Has type 'Type[int]'  
  3. c = type(a)   # Also has type 'Type[int]'  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...