Skip to main content
 首页 » 编程设计

python之类型提示 : How can I indicate that I want to return an instance of the actual class

2024年10月17日8yyy_WW

<分区>

当我尝试将类型提示和对象创建结合起来时 classmethod 我得到以下 NameError:

NameError: name 'Person' is not defined 

如何通过类型提示表明我想返回一个 我当前正在定义的类的实例? (见示例)


例子:

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

class Person: 
 
    def __init__(self, name: str): 
        self.name = name 
 
    @classmethod 
    def from_dict(self, info: dict) -> Person: 
        person_obj = Person(info['name']) 
        return person_obj 
 
    def speak(self, word: str) -> str: 
        print(word) 
        return self.name + 'said' + word