任何方式获得"接口"用Cython?

时间:2016-12-26 05:27:11

标签: python cython

我的应用程序需要有几个继承自单个基类的Cython cdef类,但仍然实现了许多接口。这些接口将用于对类进行isinstance()检查,以确保它们符合某些接口。

我知道Cython不支持多重继承,但是有任何方法可以实现类似接口的行为。这似乎是Cython的一个相当明显的限制,我确定我不是唯一遇到这个问题的人。

1 个答案:

答案 0 :(得分:3)

当你面对一个你无法改变但你想要与一个界面联系的基类时,你就像在纯Python中那样完全这样做:你使用abstract base classes module

有两种选择可供选择:

  1. register您的班级属于某个界面("抽象基类"),就像我为InterfaceA所做的那样,或者
  2. 您为界面设置__subclasshook__,允许其使用正确的方法声明任何课程,例如我为InterfaceB所做的。
  3. 示例:

    import abc
    
    # define the interfaces as normal (non-Cython) Python classes
    class InterfaceA(metaclass=abc.ABCMeta):
        # Python3 syntax. metaclasses are slightly different in python2   
        pass
    
    class InterfaceB(metaclass=abc.ABCMeta):
        @abc.abstractmethod
        def useful_function(self):
            raise NotImplementedError()
    
        @classmethod
        def __subclasshook__(cls,other_cls):
            if cls is InterfaceB:
                if any("useful_function" in B.__dict__ for B in C.__mro__):
                    return True
            return NotImplemented
    
    
    # our Cython class
    cdef class C:
        def useful_function(self):
            return 1
    
    c = C()
    
    print(isinstance(c,InterfaceA)) # prints False
    InterfaceA.register(C)
    print(isinstance(c,InterfaceA)) # prints True
    print(isinstance(c,InterfaceB)) # prints True
    
相关问题