我正在尝试在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也知道返回类型和自动完成功能!

关于python - 如何在Python3.7/3.8中使用通用namedtuple?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58621195/

10-12 19:38