我想知道在以下情况下如何使用类型提示来定义“ 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