Riccardo Gilardi
Riccardo Gilardi

Reputation: 63

Limit the possible values for an attribute in a Python Class

I'm trying to build a class in python describing a wheel position I want it to be limited to 4 values ("FL", "FR", "RL", "RR")

But now when I try to create a class for the WheelPos attribute and limit its values, both using Enum and __slots__, this doesn't prevent me from choosing any value I like for the attribute.

Is there an instrument in python to say the attribute values to stick within a finite list?

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

Upvotes: 2

Views: 2043

Answers (1)

Riccardo Gilardi
Riccardo Gilardi

Reputation: 63

I resolved the issue by myself in the meanwhile, so I'm posting the answer in case it could help anyone in the future.

I limited the WheelPos attribute values describing it as an Enum object and then introducing a "control function" which check if the init function for any wheel object is within the enum values

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

Hence even out of the car class definition I am assured only "right" values for the wheel attributes can be called

Upvotes: 3

Related Questions