为什么只有在构造函数有参数时才需要泛型?


from typing import TypeVar
T = TypeVar('T')
class MyList:
def __init__(self):
self.my_list: list[T] = []
class MyListWithX:
def __init__(self, x: int):
self.my_list: list[T] = []
第一个类工作正常,第二个类抛出以下错误
main.py:11: error: Type variable "main.T" is unbound                                                   
main.py:11: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)  
main.py:11: note: (Hint: Use "T" in function signature to bind "T" inside a function) 

它告诉如何修复它,即而不是我的问题是

为什么我需要使用泛型只有当我的构造函数有一个参数(自我排除)

不是你的构造函数有一个参数,而是它有一个类型注释(恰好在你的参数上)。默认情况下,只在定义中有类型注释的函数上启用类型检查。

from typing import TypeVar
T = TypeVar('T')
class MyList:
def __init__(self) -> None:
self.my_list: list[T] = []

你会看到错误。

最新更新