Reputation: 11
I'm familiarizing myself with Python, and I have a question on rewriting attributes with illegal values.
Suppose I have a class Human, with attribute limbs, like so:
class Human:
def __init__(self, limbs):
if limbs > 4:
raise ValueError('Humans dont have more than 4 limbs.')
self.limbs = limbs
h1 = Human(5) # Raises error - good.
h2 = Human(4)
h2.limbs = 5 # How do I protect against this?
Setting the limbs attribute to 5 would be caught via the constructor, but it is allowed via direct assignment. Is there a way to enforce error checking on attribute assignment? Should I be using an immutable string/tuple?
Again, I'm very new so I apologize if this is a silly question. Thanks!
Upvotes: 1
Views: 164
Reputation: 3524
You could use the property
decorator to make getters and setters for your property.
class Human(object):
def __init__(self, limbs):
self.limbs = limbs
@property
def limbs(self):
return self._limbs
@limbs.setter
def limbs(self, new_value):
if new_value > 4:
raise ValueError("Humans don't have more than 4 limbs.")
self._limbs = new_value
human = Human(4)
human.limbs = 5 # This will raise an exception
That said, if someone really wants to change this, they can still set self._limbs
to whatever they want.
EDIT: Updated the example to use the setter in the constructor per @chepner's comment.
Upvotes: 4