为什么在python中使用typing.Generic时保留cls关键字属性?
为什么在python中使用typing.Generic时保留cls关键字属性?,python,python-3.x,typing,mypy,Python,Python 3.x,Typing,Mypy,Generic类(我将使用Python3.7+)是如何限制cls作为\uuuu init\uuu中的关键字参数的使用的 这很清楚: >>> from typing import Generic, TypeVar >>> I = TypeVar("I") >>> class A(Generic[I]): ... def __init__(self, cls=1): ... pass ... >>> A
Generic
类(我将使用Python3.7+)是如何限制cls
作为\uuuu init\uuu
中的关键字参数的使用的
这很清楚:
>>> from typing import Generic, TypeVar
>>> I = TypeVar("I")
>>> class A(Generic[I]):
... def __init__(self, cls=1):
... pass
...
>>> A(1) # No error
>>> A(cls=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __new__() got multiple values for argument 'cls'
>>输入import Generic,TypeVar
>>>I=类型变量(“I”)
>>>A类(通用[I]):
... 定义初始化(自,cls=1):
... 通过
...
>>>A(1)#没有错误
>>>A(cls=1)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:\uuuuu new\uuuuuuu()为参数“cls”获取了多个值
这看起来像是Generic
所特有的。谢谢根据:
这里我们可以看到它使用cls
作为名称,因此您不能在**kwds
中传递另一个名称
def __new__(cls, *args, **kwds):
if cls in (Generic, Protocol):
raise TypeError(f"Type {cls.__name__} cannot be instantiated; "
"it can be used only as a base class")
if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
obj = super().__new__(cls)
else:
obj = super().__new__(cls, *args, **kwds)
return obj