我尝试在 Python 3.7(和 3.8)中使用通用命名元组功能,但解释器会引发错误。我用的方法不好吗?
from typing import NamedTuple, TypeVar, Generic
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
T = TypeVar("T")
class MyResult(NamedTuple, Generic[T]):
Body: T
Status: int
def func1() -> MyResult[Person]:
return MyResult(Person('asghar',12), 200)
引发以下错误:
Traceback (most recent call last):
File "/Users/kamyar/Documents/generic_named_tuple.py", line 16, in <module>
def func1() -> MyResult[Type[Person]]:
TypeError: 'type' object is not subscriptable
感谢@shynjax287,我使用了解决方法来修复代码:
from typing import NamedTuple, TypeVar, Generic, Type
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
T = TypeVar("T")
class MyResult(NamedTuple):
Body: T
Status: int
class MyResultGeneric(MyResult, Generic[T]):
pass
def func1() -> MyResultGeneric[Person]:
return MyResultGeneric[Person](Person('asghar',12), 200)
print(func1().Body.name)
即使 PyCharm 也知道返回类型并且自动完成功能也能正常工作!