问题描述
我正在尝试使用函数注释,希望我的编辑器能够更好地重构.但是,我遇到了以下问题:
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
.
这里我调用类对象,因为根据您的代码示例,.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.
这篇关于抽象类子类的函数注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!