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'
i am new comer here....how can i post here about python related problem.