python - 限制 Python 类中属性的可能值

标签 python class attributes

我正在尝试用 python 构建一个类来描述车轮位置 我希望将其限制为 4 个值 ("FL", "FR", "RL", "RR")

但是现在,当我尝试使用 Enum__slots__ 为 WheelPos 属性创建一个类并限制其值时,这并不妨碍我选择任何我喜欢该属性的值。

Python 中是否有一种工具可以表示要保留在有限列表中的属性值?

from operator import attrgetter

class WheelPos():
    __slots__ = ("FL", "FR", "RL", "RR")

class wheel(object):
    def __init__(self, WheelPos, pressure):
        self.WheelPos = WheelPos
        self.pressure = pressure

class car(object):
    wheel1 = wheel(1,3)
    wheel2 = wheel("front_left",3)
    wheel3 = wheel("RL",3)
    wheel4 = wheel("RR",3) 

    wheels = [wheel1, wheel2, wheel3, wheel4]
  
    def __init__(self, name):
        self.name = name
macchina = car("micra")
print(macchina.wheel1.WheelPos)
print(macchina.wheel2.WheelPos)
print(macchina.wheel3.WheelPos)
out: 1, front_left, RL

最佳答案

同时我自己解决了这个问题,所以我发布答案,以防将来对任何人有帮助。

我限制了 WheelPos 属性值,将其描述为枚举对象,然后引入一个“控制函数”,该函数检查任何车轮对象的 init 函数是否在枚举值内

from enum import Enum
    
class wheel(object):
    class WheelPos(Enum):
        FL = "FL"
        FR = "FR"
        RL = "RL"
        RR = "RR"
    
    def __init__(self, WheelPos, pressure):
        self._set_WheelPos(WheelPos)
        self.pressure = pressure

    def _set_WheelPos(self, WheelPos):
        if WheelPos in set(item.value for item in self.WheelPos):
            self.WheelPos = WheelPos
        else:
            raise ValueError("Wheel Position value not valid")

class car(object):
    wheel1 = wheel("FL",3)
    wheel2 = wheel("FR",3)
    wheel3 = wheel("RL",3)
    wheel4 = wheel("RR",3) 

    wheels = [wheel1, wheel2, wheel3, wheel4]
  
    def __init__(self, name):
        self.name = name

因此,即使在汽车类定义之外,我也确信只能调用车轮属性的“正确”值

关于python - 限制 Python 类中属性的可能值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71972265/

相关文章:

python - matplotlib 中的 3D 离散热图

python - img src=blob : how to download image?

java - 类静态初始化 block 内的类使用

c++ - 创建指向非静态类成员函数的类成员指针函数变量

javascript - 如何在 Zend Framework 中附加 js 文件时定义自定义属性?

jquery如何找到根据属性名称搜索的元素

c# - 使用 BindAttribute 附加到子类 MVC3 模型中的白名单

python - 使用 Django Tables2 为对话框添加单击事件

python - Scrapy LinkExtractor - 要遵循哪个 RegEx?

python - "Ambiguous Class Definition"类名 "I"(Python 中的 Pep8)