如何从基类提示备用构造函数的返回类型

时间:2019-07-03 15:53:26

标签: python python-3.x python-typing

我想知道在以下情况下如何使用类型提示来定义“ load”函数的返回类型:

class BaseClass:

    @classmethod
    def load(cls, path) -> '??????':  # Should return a cls object
        constructor_args = load_from_file(path)
        return cls(**constructor_args)

class ImplementationClass(BaseClass):
    ...

我希望在IDE中具有自动类型推断功能,以指示my_implementation将是ImplementationClass实例:

my_implementation = ImplementationClass.load('/path/to/file.pkl') 

有没有办法在Python中做到这一点?

答案:

此问题已正确标记为重复。在这种情况下,正确答案(基于answer to the original question)是

from typing import TypeVar, Type

T = TypeVar('T', bound = 'BaseClass')

class BaseClass:

    @classmethod
    def load(cls: Type[T], path) -> T:  # Should return a cls object
        constructor_args = load_from_file`(path)
        return cls(**constructor_args)

class ImplementationClass(BaseClass):

    def my_method(self):
        pass


my_instance = ImplementationClass.load('/path/to/file')
my_instance.my_method()  # Type checker is happy with this line now

0 个答案:

没有答案