抽象类子类的函数注解 [英] Function annotation for subclasses of abstract class

查看:38
本文介绍了抽象类子类的函数注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用函数注释,希望我的编辑器能够更好地重构.但是,我遇到了以下问题:

I'm trying to use function annotations in the hope that my editor will be better at refactoring. I however am stumbling over the following problem:

我有一个抽象基类算法.

I have an abstract base class Algorithm.

class Algorithm(metaclass=ABCMeta):
     def __init__(self):   
          self.foo = 'bar'

我还有一个使用算法子类实例的函数

I also have a function that uses instances of subclasses of Algorithm

def get_foo(foo_algorithm):
    return foo_algoritm.foo

输入的 foo_algorithm 可以是 Algorithm 的任何子类的实例.我如何明智地注释此输入?我正在寻找类似的东西:

the input foo_algorithm can be an instance of any of the subclasses of Algorithm. How do I sensibly annotate this input? I'm looking for something along the lines off:

def get_foo(foo_algorithm: subclassof(Algorithm)):
    return foo_algoritm.foo

但我找不到正确的方法来做到这一点.

But I couldn't find the right way to do this.

推荐答案

直接使用Algorithm:

def get_foo(foo_algorithm: Algorithm):
    return foo_algoritm.foo

并且自动子类的任何实例都是可以接受的(isinstance(foo_algorithm, Algorithm) 必须为真,这适用于基类的所有子类).

and automatically any instance of a subclass will be acceptable (isinstance(foo_algorithm, Algorithm) must be true, which applies to all subclasses of a baseclass).

如果你只能接受,那么使用Type[Algorithm]作为类型提示:

If you can only accept classes, then use Type[Algorithm] as the type hint:

def get_foo(foo_algorithm: Type[Algorithm]):
    return foo_algoritm().foo

参见类型PEP 484 的类对象部分 -- 类型提示:

有时您想谈论类对象,特别是从给定类继承的类对象.这可以拼写为 Type[C],其中 C 是一个类.澄清:C(当用作注解时)指的是 C 类的实例,Type[C] 指的是 的子类>C.

Sometimes you want to talk about class objects, in particular class objects that inherit from a given class. This can be spelled as Type[C] where C is a class. To clarify: while C (when used as an annotation) refers to instances of class C, Type[C] refers to subclasses of C.

这里我调用类对象,因为根据您的代码示例,.foo 是一个实例属性;从Algorithm 派生的类本身不会有这样的属性.

Here I called the class object, since .foo is an instance attribute according to your code example; a class derived from Algorithm would not have such an attribute itself.

这篇关于抽象类子类的函数注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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