【发布时间】:2021-08-11 22:48:25
【问题描述】:
假设我有一个名为 Summable 的 PEP-544 协议:
class Summable(Protocol):
@property
total_amount()-> Decimal:
...
我有实现Protocol的模型Item
class Item(Summable, models.Model):
discount = models.DecimalField(
decimal_places=2,
validators=[MaxValueValidator(1)],
default=Decimal('0.00'),
max_digits=10
)
price = models.DecimalField(
decimal_places=4,
validators=[MinValueValidator(0)],
max_digits=10
)
@property
def total_amount(self) - > Decimal:
return self.price - self.price * self.discount
class Meta:
ordering = ['id']
我明白了:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
即使我从 Summable.Meta 和 models.Model.Meta 扩展 Item 的 Meta 也会发生同样的情况。
我正在使用 python 3.9
有什么想法吗?
【问题讨论】:
-
注意
Item没有实现Summable协议!total_amount: Decimal意味着可读的和可写的属性。一个普通的@property只能读取。 -
非常有趣的一点
-
@MisterMiyagi 那么您对协议中只读字段的建议是我目前的更正吗?即用
@property声明它 -
感谢您发现只是在玩打字 python,这一切都很迷人 xD
-
最简单的解决方法是在协议中也将
total_amount定义为@property。
标签: python python-3.x django protocols pep