为什么在使用打字时会保留cls关键字属性。python中的泛型?

问题描述 投票:2回答:1

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特有的内容。谢谢

python python-3.x typing mypy
1个回答
2
投票

根据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中传递另一个。

© www.soinside.com 2019 - 2024. All rights reserved.