[英]How should one do upper level method that returns self with python pep484 type checking
如何在类中定义函数,使函数的返回类型为“当前类” - 而不是基类。 例如:
Class Parent:
def set_common_properties_from_string( input : str ) -> <WHAT SHOULD BE HERE>
# Do some stuff you want to do in all classes
return self
Class Child( Parent ):
pass
def from_file( filename : str ) -> 'Child'
return Child().set_common_properties_from_string() # The return type of set_common must be Child
或者应该以某种方式投射它? 如果返回类型是baseclass,那么它将给出错误。
我知道可以将它放到两行并添加用于保持Child()的临时变量,但我认为一个衬里更好看。
我使用mypy进行类型检查。
您可以使用新实现的(仍然是实验性的) 通用自我功能,这是一种旨在帮助您解决所遇问题的机制。
Mypy支持版本 0.4.6的“通用自我”功能(注意:截至撰写本文时,mypy的最新版本为0.470)。 不幸的是,如果其他PEP 484兼容类型检查器支持此功能,我不记得我的头脑。
简而言之,您需要做的是创建一个新的TypeVar,显式地注释您的self
变量以具有该类型,并且还将该TypeVar作为返回值。
因此,在您的情况下,您需要将代码修改为以下内容:
from typing import TypeVar
T = TypeVar('T', bound='Parent')
class Parent:
def set_common_properties(self: T, input: str) -> T:
# Do some stuff you want to do in all classes
return self
class Child(Parent):
def from_file(self, filename: str) -> 'Child':
# More code here
return Child().set_common_properties(...)
请注意,我们需要将我们的TypeVar设置为由Parent
类绑定 - 这样,在set_common_properties
方法中,我们就可以调用Parent
任何其他方法。
您可以在mypy的网站和PEP 484中找到更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.