vendredi 6 juillet 2018

Inherent python abstract base class in django

I would like to make an generic module in python which uses data from a Django model, and use typing to document the interface. The module should be independent of the Django model. How should this by done in a pythonic way?

I'm thinking of using ABC class, the independent python file should then be something like (shape.py):

from abc import ABC


class Shape(ABC):
    @property
    @abstractmethod
    def height(self) -> float:
         pass

    @property
    @abstractmethod
    def area(self) -> float:
         pass


class VolumeCalculation:
    def __init__(self, shape: Shape) -> None:
        self.shape = shape

    def volume(self) -> float
        return self.shape.area*self.shape.height

While the django model is defined in another file:

from django.db import models
from shape import Shape


class Box(models.Model, Shape):
    height= models.FloatField('height')
    area = models.FloatField('area')

When I do this I get the following error:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Alternatively I can remove the base class and construct VolumeCalculation with the needed parameters from Shape. But as the real object contains many parameters the list becomes quite long.

Aucun commentaire:

Enregistrer un commentaire