Type-Hints: 如何表明我想要返回实际类的实例?

2024-10-01 22:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图通过 一个classmethod我得到以下NameError

NameError: name 'Person' is not defined

如何通过类型提示指示我要返回 我当前定义的类的实例?(参见示例)


示例:

classmethodfrom_dict的定义失败,因为Python无法解析class Person。在

^{pr2}$

Tags: 实例name示例类型定义isnotdict
2条回答

使用字符串:

@classmethod
def from_dict(self, info: dict) -> 'Person':
    person_obj = Person(info['name'])
    return person_obj

这使得类方法的返回类型为Person。这在编写相互依赖的类时也很有用。在

您需要使用TypeVar。在

from typing import TypeVar
PersonType = TypeVar("PersonType", bound="Person")

class Person:
    @classmethod
    def from_dict(self, info: dict) -> PersonType:
        person_obj = Person(info['name'])
        return person_obj

相关问题 更多 >

    热门问题