Mec*_*Pig 5 python typing magic-methods
参考Python文档__class_getitem__:
\n\n一个类通常只有在定义了特殊的类方法时才可以被参数化
\n__class_getitem__()。
并输入:
\n\n\n自 3.9 版起已弃用:
\nbuiltins.type现在支持[]. 请参阅PEP 585和通用别名类型。
这意味着在3.9版本之后,我们可以使用type[class]代替typing.Type[class],但是在pycharm中,当我使用前者时,IDE告诉我:
\n\n类
\ntypeundefined__getitem__,因此,[]不能在其实例上使用该运算符。
我在交互式 Python 中证实了这一点:
\nPython 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32\nType "help", "copyright", "credits" or "license" for more information.\n>>> list[int]\nlist[int]\n>>> list.__class_getitem__(int)\nlist[int]\n>>> type[int]\ntype[int]\n>>> type.__class_getitem__(int)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nAttributeError: type object \'type\' has no attribute \'__class_getitem__\'\n>>> type.__getitem__(int)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nAttributeError: type object \'type\' has no attribute \'__getitem__\'. Did you mean: \'__setattr__\'?\nRun Code Online (Sandbox Code Playgroud)\n我注意到第一个文档中“一般”是用斜体标记的,这意味着不能保证它对于所有类型都是正确的,所以并不意味着这里的文档是错误的。但我不明白为什么Python采用特殊的实现type(因为它是一个元类?)。IDE不断的警告可能会让我放弃使用转而type使用typing.Type。
更新:
\n从第一个文档我们可以知道type没有实现该__getitem__方法的原因:
\n\n通常,使用方括号订阅对象将调用
\n__getitem__()object\xe2\x80\x99s 类上定义的实例方法。然而,如果被订阅的对象本身就是一个类,则__class_getitem__()可以调用类方法。如果定义正确,__class_getitem__()应该返回一个GenericAlias对象。
因此,type没有实现__getitem__避免出现类似 的类型int[str]。然而,这并不是 type 不实现__class_getitem__. 即使有这个实现,根据文档描述,也不会影响type.