gpt4 book ai didi

python - 为什么在python中使用typing.Generic时保留了cls关键字属性?

转载 作者:行者123 更新时间:2023-12-04 09:43:20 25 4
gpt4 key购买 nike

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 中传递另一个.

关于python - 为什么在python中使用typing.Generic时保留了cls关键字属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62235830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com