【问题标题】:Function annotation for subclasses of abstract class抽象类子类的函数注解
【发布时间】:2016-12-12 00:24:37
【问题描述】:

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

我有一个抽象基类算法。

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

但我找不到正确的方法。

【问题讨论】:

  • 你的问题有点不清楚。你说的好像你的get_foo 会接受Algorithm子类,而不是Algorithm 子类的instance。您的代码另有说明; .foo__init__ 方法中设置,因此必须是实例属性。它不会出现在类对象上。
  • 好点,已编辑。它确实是我正在使用的实例化子类。
  • 好吧,无论哪种方式,我现在都涵盖了。
  • 谢谢你解决了我的问题,我猜python总是比我想象的简单:)。

标签: python python-3.x annotations type-hinting


【解决方案1】:

直接使用Algorithm即可:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多