【问题标题】:How to document a type of the variable that can be an object of any kind that implements an interface in Python?如何记录可以是在 Python 中实现接口的任何类型的对象的变量类型?
【发布时间】:2017-07-14 10:33:56
【问题描述】:

我有如下结构的代码:

一个接口ISomething(即一个基本抽象类):

class ISomething:
    # some methods that should be implemented in classes
    # that implement this interface

实现ISomething接口的各种类:

class SomethingA(ISomething):
    # implementation of the interface

class SomethingB(ISomething):
    # implementation of the interface
(...)
class SomethingZ(ISomething):
    # implementation of the interface

我的其他类在构造函数中需要 SomethingASomethingB、...、SomethingZ 类之一的对象:

def __init__(self, something):
    '''
    Constructor

    :param something: Param description
    :type something: *Anything that implements ISomething interface*
    '''

    self._something = something

如您所见,我使用Sphing Docstring。不过,我正在寻找一般的答案。

我的问题是:如何证明一个变量是任何实现 ISomething 接口的类的对象。

目前,我将此变量的类型记录为“列表中的一个”,即:

:type something: SomethingA|SomethingB|...|SomethingZ

但是,我不确定这是否是最好的方法。我觉得还是保持一般性比较好。

【问题讨论】:

  • “一般答案”是什么意思?为什么“实现 ISomething 接口的任何东西”不够好?
  • 我更喜欢某种符号。当然,我不确定这样的符号是否存在。
  • @Marein:应该是:type something: ISomething
  • 因为在 Python 中,“接口”只是其他类的子类,所以仅仅说 :type something: ISomething 就足够了吗? (感谢@mzjn 的更正)
  • @Marein 您是否可以根据您的评论创建答案?我希望能够给予赏金:)

标签: python interface python-sphinx docstring


【解决方案1】:

由于在 Python 中,“接口”只是其他类的子类,因此只需说 :type something: ISomething 就足够了。

全文:

class ISomething:
    # some methods that should be implemented in classes
    # that implement this interface

class SomethingA(ISomething):
    # implementation of the interface

class SomethingB(ISomething):
    # implementation of the interface

class OtherClass:
    def __init__(self, something):
        '''
        Constructor

        :param something: Param description
        :type something: ISomething
        '''

       self._something = something

【讨论】:

    【解决方案2】:

    我会使用 :precondition:

    :前置条件:isinstance(something, ISomething)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多