如何记录变量的类型,该变量可以是在Python中实现接口的任何类型的对象?

时间:2017-07-14 10:33:57

标签: python interface documentation python-sphinx docstring

我有以下结构的代码:

接口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

但是,我不确定这是否是最佳方法。我觉得保持它更加通用会更好。

2 个答案:

答案 0 :(得分:2)

因为在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

答案 1 :(得分:1)

我会使用:precondition:

:前提条件:isinstance(某事,ISomething)