我正在尝试用 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/