【问题标题】:Type-Hints: How can I indicate that I want to return an instance of the actual class? [duplicate]类型提示:如何表明我想要返回实际类的实例? [复制]
【发布时间】:2017-03-15 13:41:17
【问题描述】:

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

NameError: name 'Person' is not defined

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


例子:

classmethodfrom_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

【问题讨论】:

    标签: python python-3.5 typing type-hinting


    【解决方案1】:

    您需要使用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
    

    【讨论】:

      【解决方案2】:

      使用字符串:

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

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

      【讨论】:

        猜你喜欢
        • 2020-07-24
        • 2021-03-11
        • 2013-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多