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

2024-09-30 01:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下结构的代码:

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

我的另一个类需要构造函数中的类SomethingASomethingBSomethingZ之一的对象:

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

然而,我不确定这是否是最好的方法。我觉得最好是保持它的概括性。你知道吗


Tags: ofthe对象selfthattype记录something
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

我将使用:前提条件:

:前提条件:isinstance(something,something)

相关问题 更多 >

    热门问题