2024-10-01 22:27:26 发布
网友
当我试图通过 一个classmethod我得到以下NameError:
classmethod
NameError
NameError: name 'Person' is not defined
如何通过类型提示指示我要返回 我当前定义的类的实例?(参见示例)
示例:
classmethodfrom_dict的定义失败,因为Python无法解析class Person。在
from_dict
class Person
使用字符串:
@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
使用字符串:
这使得类方法的返回类型为Person。这在编写相互依赖的类时也很有用。在
您需要使用TypeVar。在
相关问题 更多 >
编程相关推荐