Generic
类(我将使用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
中传递另一个。