Jul-03-2020, 01:05 PM
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.
Limiting valid values for a variable in a class
|
Jul-03-2020, 01:05 PM
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.
Jul-03-2020, 01:10 PM
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.
I welcome all feedback.
The only dumb question, is one that doesn't get asked. My Github How to post code using bbtags Download my project scripts
Jul-03-2020, 01:36 PM
(This post was last modified: Jul-03-2020, 01:36 PM by Gribouillis.)
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 ValueErrorIt 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'
Jul-06-2020, 06:52 AM
Thank you!!
Jul-06-2020, 07:01 AM
i am new comer here....how can i post here about python related problem.
Jul-06-2020, 07:17 AM
@Monira Read the "Posting a new thread" topic in the Help/Rules page.
|
|