创建python类时的强属性类型检查

2024-09-26 17:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自Java背景,我习惯于POJO来定义数据模型。基本上,我想定义的是一个数据模型,它使用Python类进行强属性类型检查,并且不能添加比所定义的属性更多的属性(基本上类似于django模型)。例如,我尝试创建一个类:

class A:
    element1: int
    element2: str

但这样我并不是强迫一个对象没有属性element3

pythonic实现这个目标的方法是什么,您对python3.6+有什么建议吗


Tags: django模型类型属性定义java数据模型class
1条回答
网友
1楼 · 发布于 2024-09-26 17:43:12

您可以使用__slots__来实现这一点,您可以使用magic方法__slots__在这里找到更多信息:Slots docs

Slots are a nice way to work around this space consumption problem. Instead of having a dynamic dict that allows adding attributes to objects dynamically, slots provide a static structure which prohibits additions after the creation of an instance.

请记住,这是有代价的

It will break serialization (e.g. pickle). It will also break multiple inheritance. A class can't inherit from more than one class that either defines slots or has an instance layout defined in C code (like list, tuple or int).

我希望这些信息是足够的

相关问题 更多 >

    热门问题