Using a Rectangle Class in Python

This week’s assignment was about working with classes and objects in Python. I implemented a Rectangle class using object-oriented programming and tested it with several helper functions.

Code Procedure:

  1. Created a Point class to represent the (x, y) corner of a rectangle.

  2. Defined a Rectangle class that stores position, width, and height.

  3. Implemented the following helper functions:

    • create_rectangle(x, y, width, height) - creates a new Rectangle instance.

    • str_rectangle(rect) - returns a string representation of the rectangle.

    • shift_rectangle(rect, dx, dy) - modifies the rectangle’s position in place.

    • offset_rectangle(rect, dx, dy) - returns a new rectangle offset from the original.

  4. Tested the functions using the example given in the assignment to ensure they worked as expected.

This assignment helped me understand how class instances can be passed into and returned from functions, and how methods like __str__ improve output readability.


Code:

# Supporting Point class

class Point:

    def __init__(self, x, y):

        self.x = x

        self.y = y

        

    def __str__(self):

        return f"({self.x}, {self.y})"


# Rectangle class

class Rectangle:

    """ A class to manufacture rectangle objects """


    def __init__(self, posn, w, h):

        self.corner = posn

        self.width = w

        self.height = h


    def __str__(self):

        return f"({self.corner.x}, {self.corner.y}, {self.width}, {self.height})"


# Function to create a rectangle

def create_rectangle(x, y, width, height):

    return Rectangle(Point(x, y), width, height)


# Function to return string representation

def str_rectangle(rect):

    return str(rect)


# Function to shift rectangle in-place

def shift_rectangle(rect, dx, dy):

    rect.corner.x += dx

    rect.corner.y += dy


# Function to return a new shifted rectangle

def offset_rectangle(rect, dx, dy):

    return Rectangle(Point(rect.corner.x + dx, rect.corner.y + dy), rect.width, rect.height)


# Test Code

r1 = create_rectangle(10, 20, 30, 40)

print(str_rectangle(r1))


shift_rectangle(r1, -10, -20)

print(str_rectangle(r1))


r2 = offset_rectangle(r1, 100, 100)

print(str_rectangle(r1))  # should be same as previous

print(str_rectangle(r2))


Output:

(10, 20, 30, 40)
(0, 0, 30, 40)
(0, 0, 30, 40)
(100, 100, 30, 40)


This assignment helped solidify my understanding of how object instances can be manipulated directly or copied and modified through functions. It also reinforced the difference between changing an object in place vs. returning a new one.

Comments

Popular posts from this blog

Python Assignment – Intro to Functions and Lists

Python Assignment - Roots & Reciprocals