在 python 类型提示中,如何让参数接受基类的任何子类? [英] In python type-hinting, how can I make an argument accept any subclass of a base class?

查看:24
本文介绍了在 python 类型提示中,如何让参数接受基类的任何子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来有点像这样的函数.我希望该函数接受 io.IOBase 的任何子类 - 换句话说,任何类似文件的对象.

I have a function that looks a bit like this. I want the function to accept any subclass of io.IOBase - in other words, any file-like object.

def import_csv_file(f:io.IOBase)->pandas.DataFrame:
    return pandas.read_csv(f)

当我在 IntelliJ 中查看对象时,类型提示的 JetBrains 实现会拒绝任何输入,除非我提供了一个 io.IOBase 的实例——但是如果我想传入一个 io.IOBase 的子类的实例怎么办?数据库?有没有办法改变类型提示以说这是允许的?

When I view the object in IntelliJ, the JetBrains implementation of type-hinting rejects any input unless I provide exactly an instance of io.IOBase - but what if I want to pass in an instance of a sub-class of io.IOBase? Is there a way to change the type-hint to say that this is allowed?

推荐答案

如果您使用基类(io.IOBase 在您的情况下)注释函数参数,那么您还可以传递任何基类的子类型——继承也适用于注解类型.

If you annotate a function argument with the base class (io.IOBase in your case) then you can also pass instances of any subtype of the base class – inheritance applies to annotation types as well.

也就是说,您可以使用 typing.IO 作为表示任何 I/O 流的泛型类型(以及分别用于二进制和文本 I/O 流的 typing.TextIOtyping.BinaryIO).

That said, you could use typing.IO as a generic type representing any I/O stream (and typing.TextIO and typing.BinaryIO for binary and text I/O streams respectively).

这篇关于在 python 类型提示中,如何让参数接受基类的任何子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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