[英]Inherent python abstract base class in django
我想在python中创建一个通用模块,它使用来自Django模型的数据,并使用输入来记录接口。 该模块应独立于Django模型。 应该如何以pythonic方式完成?
我正在考虑使用ABC类,那么独立的python文件应该类似于(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
django模型在另一个文件中定义:
from django.db import models
from shape import Shape
class Box(models.Model, Shape):
height= models.FloatField('height')
area = models.FloatField('area')
当我这样做时,我收到以下错误:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
或者,我可以删除基类并使用Shape中的所需参数构造VolumeCalculation。 但由于真实对象包含许多参数,因此列表变得非常长。
您不必从Shape
派生Box
以使其成为Shape
,您只需注册它 :
from django.db import models
from shape import Shape
class Box(models.Model):
height= models.FloatField('height')
area = models.FloatField('area')
Shape.register(Box)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.