Skip to content

Instantly share code, notes, and snippets.

@lol97
Created December 26, 2023 05:09
Show Gist options
  • Select an option

  • Save lol97/e4c1245f9e26ed8d08104589dce69692 to your computer and use it in GitHub Desktop.

Select an option

Save lol97/e4c1245f9e26ed8d08104589dce69692 to your computer and use it in GitHub Desktop.
class Rectangle:
def __init__(self, length, width):
self._length = length
self._width = width
# Check the invariant after initializing the attributes
self._check_invariant()
def _check_invariant(self):
# Invariant: Both length and width must be positive
if self._length <= 0 or self._width <= 0:
raise ValueError("Invariant violation: Length and width must be positive.")
@property
def length(self):
return self._length
@length.setter
def length(self, value):
self._length = value
# Check the invariant after modifying the attribute
self._check_invariant()
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Check the invariant after modifying the attribute
self._check_invariant()
# Example usage:
try:
# Creating a rectangle with invalid dimensions
invalid_rectangle = Rectangle(-2, 5)
except ValueError as e:
print(e)
# Creating a valid rectangle
valid_rectangle = Rectangle(4, 3)
print("Length:", valid_rectangle.length)
print("Width:", valid_rectangle.width)
# Modifying attributes and maintaining the invariant
valid_rectangle.length = 7
valid_rectangle.width = 2
print("Modified Length:", valid_rectangle.length)
print("Modified Width:", valid_rectangle.width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment