Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在python中使用typing.Generic时保留cls关键字属性?_Python_Python 3.x_Typing_Mypy - Fatal编程技术网

为什么在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