Python Forum

Full Version: Limiting valid values for a variable in a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is it possible to limit the values of a variable of a class? Say I have a class Vehicle with variables Type, Make, Model, etc and I want to limit the values of Type to "sedan", LDV, SUV and 4X4.
Not sure I really understand the question but, you can a have a predefined list of types. If it's not in the list throw a message instead of setting the variable.
You can do it by defining a property

class Foo:
    _spam_values =  set(["sedan", "LDV", "SUV", "4X4"])

    def __init__(self, spam):
        self.spam = spam

    @property
    def spam(self):
        return self._spamspamspam

    @spam.setter
    def spam(self, value):
        if value not in self._spam_values:
            raise ValueError('Invalid spam value', value, 'Expected one of', self._spam_values)
        self._spamspamspam = value

foo = Foo('LDV')
foo.spam = 'SUV'   # OK
foo.spam = 'ham'   # KO, raises ValueError
It could be sytematized somewhat by using the descriptor protocol:
class ConstrainedMember:
    def __init__(self, name, values, store_name=None):
        self.name = name
        self.values = set(values)
        self.store_name = store_name or ('_' + name)
        
    def __get__(self, obj):
        return getattr(obj, self.store_name)
    
    def __set__(self, obj, value):
        if value not in self.values:
            raise TypeError('Invalid value for member', self.name,
                            'Expected one of', self.values,
                            'got', value)
        setattr(obj, self.store_name, value)
        
class Foo:
    spam = ConstrainedMember('spam', ["sedan", "LDV", "SUV", "4X4"])
    
foo = Foo()
foo.spam = 'SUV'
foo.spam = 'bar'
Thank you!!
i am new comer here....how can i post here about python related problem.
@Monira Read the "Posting a new thread" topic in the Help/Rules page.