Skip to main content
 首页 » 编程设计

python之抽象类子类的函数注解

2025年05月04日26sky-heaven

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

我有一个抽象基类算法。

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

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

def get_foo(foo_algorithm): 
    return foo_algoritm.foo 

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

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

但我找不到正确的方法。

请您参考如下方法:

直接使用算法即可:

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

自动接受子类的任何实例(isinstance(foo_algorithm, Algorithm) 必须为真,这适用于基类的所有子类)。

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

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

参见 The type of class objects section PEP 484 的 类型提示:

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 派生的类本身不会有这样的属性。