如何在基类中键入提示

如何在基类中键入提示

本文介绍了mypy:基类没有属性x,如何在基类中键入提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了mypy,并且希望对其进行类型检查.

I recently discovered mypy and I want my code to be type checked with it.

我有一个Connector基类:

class Connector():
    ... some methods, but no __init__ ...

我有几个子类,它们都是连接器,但类型不同:

And I have several subclasses, they are all connectors, but of different types:

class Siphon(Connector)
    def __init__():
        short_name = "S"


class Tube(Connector)
    def __init__():
        short_name = "T"

使用这些对象时,通常将它们放在列表中:

When I use these objects, I normally put them in a list:

c1 = Siphon()
c2 = Tube()
list_connectors: List[Connector] = list()
list_connectors.append(c1)
list_connectors.append(c2)

现在让我们说我想编写一个函数以列表形式返回所有连接器的所有短名称.我会写这样的东西:

Now let's say I want to write a function to return all the short names of all the connectors, as a list. I'd write something like that:

def get_names(list_connectors: List[Connector]) -> List[str]:
    tmp_list: List[str] = list()
    for c in list_connectors:
        tmp_list.append(c.short_name)
    return tmp_list

当我这样做时,mypy抱怨:

When I do that, mypy complains:

error: "Connector" has no attribute "short_name"

这是正确的,基类连接器没有此属性,只有子类.但是所有Connector子类都将具有此属性.

Which is true, the base Class Connector doesn't have this attribute, only the subclasses. But all Connector subclasses will have this attribute.

我该如何纠正?我不能在这里使用class属性,因为我所有的子类都需要它们自己的short_name属性.

How should I correct that? I can"t use a class attribute here since all my subclasses will need their own short_name attribute.

我应该在我的get_names函数的类型提示中使用Union(在我的实际情况下,有两种以上类型的连接器,并且我的API用户可以添加自己的连接器)?

Should I use a Union in the type hinting of my get_names function (in my real life situation, there are much more than 2 types of connectors, and the user of my API could add his own)?

我也不确定是否可以编写基本的__init_函数并在子类中覆盖它,因为所有子类都具有不同的init

I'm also not sure I could write a base __init_ function and override it in the subclasses, because the subclasses all have a different init

推荐答案

您需要将该属性添加到基本类型中;您不需要为其赋值:

You'd add that attribute to the base type; you don't need to give it a value:

class Connector:
    short_name: str

这使用Python 3.6的 变量注释语法,这在Python 3.6或更高版本中是新的.它定义了 instance 属性的类型,而不是class属性(为此存在单独的语法).

This uses Python 3.6's Variable Annotation syntax, which is new in Python 3.6 or newer. It defines the type of an instance attribute, not a class attribute (for which there is a separate syntax).

否则,您可以使用注释,这时您必须给该属性一个初始值,并且是一个类属性:

You can use a comment otherwise, at which point you do have to give the attribute an initial value, and is a class attribute:

class Connector:
   short_name = ''  # type: str

这篇关于mypy:基类没有属性x,如何在基类中键入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:17