为什么在python中使用typing.Generic时cls关键字属性被保留?
Why is the cls keyword attribute reserved when using typing.Generic in python?
Generic
class(我将使用 Python 3.7+ PEP-0560)如何限制 cls
作为__init__
中的关键字参数 ?
这很清楚:
>>> 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'
这看起来像是 Generic
特有的东西。谢谢
根据 source code:
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
这里我们可以看到它使用cls
作为名字,所以你不能在**kwds
中传递另一个。
Generic
class(我将使用 Python 3.7+ PEP-0560)如何限制 cls
作为__init__
中的关键字参数 ?
这很清楚:
>>> 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'
这看起来像是 Generic
特有的东西。谢谢
根据 source code:
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
这里我们可以看到它使用cls
作为名字,所以你不能在**kwds
中传递另一个。