Middle
How to prevent assigning a negative value to a numeric field of a class in Python?
sobes.tech AI
Answer from AI
To prevent assigning a negative value to a class's numeric field in Python, you can use a property with a check in the setter. Example:
class Product:
def __init__(self, price):
self.price = price # calls the setter
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative")
self._price = value
# Usage
p = Product(100)
p.price = 50 # works
p.price = -10 # raises ValueError exception
This approach allows controlling the assignment and raising an error when attempting to set an invalid value.