Python接口断言成员变量已定义

Python interface asserting member variables are defined

我尝试在 Python 3.6 中实现一个接口(我知道它们在 Python 中不存在)。使用以下最小示例:

import time

class ModuleInterface:
    # How often the module information is updated (int in seconds).
    interval = None
    def update(self):
        raise NotImplementedError

class HardDisk(ModuleInterface):
###############################################################################
     pass # First
###############################################################################
#     def update(self):        # Second
#         time.sleep(self.interval) # Second
###############################################################################

hd = HardDisk()
hd.update()

对于第一种情况,代码应该产生 NotImplementedError。在第二种情况下,我想得到一个类似的错误,但我不知道如何在 Python 中正确地实现它。接口的想法是在未定义某些内容时产生错误。但是 interval 是定义的,这就是为什么第二种情况会产生 TypeError 的原因。然而,这不是我想要得到的那种错误。为 ModuleInterface 的所有成员断言它们必须由继承 class.

定义是完美的

您正在寻找 abc module. Exemple (Python 2.7 - you'll find py3 exemples in the 3.6 doc):

import abc
import time

class ModuleInterface(object):
    __metaclass__ = abc.ABCMeta

    # How often the module information is updated (int in seconds).
    interval = abc.abstractproperty()

    @abc.abstractmethod
    def update(self):
        """ must be implemented """

class WrongHardDisk(ModuleInterface):
    """ This one doesn't define `interval` 
        so it cannot be instanciated 
    """
    def update(self):
        time.sleep(self.interval)


class HardDisk(ModuleInterface):
    interval = 5
    def update(self):
        time.sleep(self.interval)

try:
    # Will raise a TypeError
    whd = WrongHardDisk()
except Exception as e:
    print type(e), e

# this one will work as expected
hd = HardDisk()
hd.update()

AFAICT 使其与 Python 3.6 一起工作的唯一修改应该是替换这个(未经测试):

class ModuleInterface(object):
    __metaclass__ = abc.ABCMeta
    # ...

class ModuleInterface(metaclass=abc.ABCMeta):
    # ...