mypy:基类没有属性 x,如何在基类中键入提示 [英] mypy: base class has no attribute x, how to type hint in base class

查看:30
本文介绍了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"

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

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

我该如何纠正?我不能在这里使用类属性,因为我的所有子类都需要它们自己的 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 函数的类型提示中使用联合(在我的现实生活中,连接器的类型远不止 2 种,我的 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 属性的类型,而不是一个类属性(对于它有 单独的语法).

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,如何在基类中键入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆