Answer the question
In order to leave comments, you need to log in
How to correctly set the list of possible values for an object attribute?
How to correctly set the list of possible values for an object attribute?
For example:
1) there is a Task class,
2) there is an instance of the task class,
3) it has a task.priority attribute,
4) which should take the values options = ['low', 'medium', 'high'].
As a result, I should be able to:
1) set task.priority = 'low'
2) get an error if I try to set task.priority = 'something else'
Alternatively, you can check in the class constructor if value in options , or is there a more correct one way to do it?
Answer the question
In order to leave comments, you need to log in
class Task(object):
@property
def priority(self):
return self._priority
@priority.setter
def priority(self, value):
if value not in ('low', 'high', 'medium'):
raise ValueError('Incorrect priority value')
self._priority = value
Pass the value of the variable not by assigning a value, but through the set_priority method, in which the check will be carried out. For example like this:
class Task():
def set_priority(self, priority):
if priority in ['low', 'medium', 'high']:
# Делаем что-то хорошее, например
self.priority = priority
else:
# Выводим ошибку
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question