jeudi 5 juillet 2018

Composition over Inheritance in python3

I've got some library which works with all objects supporting a certain set of methods:

- param1: np.ndarray
- method1() -> np.ndarray
- ...

Usually I'd write some base-class with these methods and let all classes which can provide these methods inherit from this base class. However, I cannot do this at the moment:

  • I cannot modify all supported classes
  • I do not want to write any wrappers for this
  • I'd have to write for each type an extra base class

Is there a possibility to write something like interfaces:

class interface1:
    @property
    @abc.abstractmethod
    def param1(self) -> np.ndarray:
        pass
class interface2:
    @abc.abstractmethod
    def method1(self) -> np.ndarray:
        pass

and match these against provided objects to make sure they support these methods?

Aucun commentaire:

Enregistrer un commentaire