如何注释返回特定类型(或子类型)的方法

2024-03-29 14:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

请考虑这段python 3.5代码:

class Foo:
    pass

class Bar(Foo):
   pass

class AbstractSomething: 

    def get_foobinator_type(self):  
        return Foo

我想给get_foobinator_type方法的返回值(using PEP-0484 annotations)加上注释:“它返回一个类型,即Foo或它的任何子类型”。你知道吗

我在Python中找不到任何明智的方法。以下是明显错误的方法:

  • 以下:def get_foobinator_type(self) -> Foo表示此方法返回Foo实例

  • Following:def get_foobinator_type(self) -> type意味着这个方法返回一个类型,但遗憾的是,没有关于它需要是Foo的子类型的信息。

用Java术语来说,我希望有一个签名为:Class<Foo> getFoobinatorType()的方法。你知道吗


Tags: 方法代码self类型getreturnfoodef
3条回答

据我所知,你真的不能。您正在寻找一种方法来指示类的返回类型;根据类的类型(即其元类)进行检查。你知道吗

问题是,元类不能帮助类型检查器评估对象的继承性,如果它是type类型的话,那没关系。你知道吗

除此之外,由于不确定使用什么类型检查器,mypy例如doesn't have support yet用于自定义元类,您可以使用这些元类将对象分组到更自定义的组中。你知道吗

在我看来,要么根本不做注释,要么更改实现并使用Foo进行注释。你知道吗

我认为您需要的是来自输入模块的TypeVar。你知道吗

from typing import TypeVar

class Foo:
    pass

class Bar(Foo):
   pass

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

class AbstractSomething: 

    def get_foobinator_type(self) -> T:  
        return Foo

From the documentation of typing

Alternatively, a type variable may specify an upper bound using bound=. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484

最近(在Python 3.5.2)引入了一个泛型Type,所以解决方案是:

class AbstractSomething: 

    def get_foobinator_type(self) -> typing.Type[Foo]:  
        return Bar

参见:python docs。你知道吗

相关问题 更多 >