Start learning free

LESSON 248 OF 569 · FUNCTIONS & CLASSES

Rectangle Class in Python: Methods That Use self

Practice O(1) Read the full explanation

A class bundles some values with the questions you can ask about them. Write a class Rectangle that remembers a rectangle's width and height, and can tell its area, its perimeter, and whether it is a square.

Implement the class Rectangle:

  • Rectangle(width, height) creates a rectangle with the given sizes.
  • area() returns the area of the rectangle: its width times its height.
  • perimeter() returns the perimeter: the length all the way around, twice the width plus twice the height.
  • isSquare() returns True if the width and the height are equal, and False otherwise.

Each line of the input is one rectangle: its width and its height. The test code first creates a Rectangle for every line, then asks each of them, in order, for its area, its perimeter and whether it is a square, and prints the three answers on one line, the boolean as True or False. So each object must keep its own sizes. The starter code spells these names the way your language does (in Go and Rust, Rectangle is a struct with methods).

 

Example 1:

Input:
    Rectangle(3, 4)
Output: 12 14 False
Explanation: The area is 3 · 4 = 12. Going around, the sides are 3 + 4 + 3 + 4 = 14.
The width and the height differ, so it isn't a square.

Example 2:

Input:
    Rectangle(5, 5)
Output: 25 20 True
Explanation: 5 · 5 = 25, and 4 sides of 5 make 20. Both sizes are 5: a square is a rectangle with equal sides.

Example 3:

Input:
    Rectangle(2, 10)
    Rectangle(10, 2)
Output:
20 24 False
20 24 False
Explanation: Two objects, each with its own sizes. Turning a rectangle on its side changes neither its area nor its perimeter.

 

Constraints:

  • 1 <= width, height <= 104
  • At most 10 rectangles per test.

Note:

Each method needs only the two sizes, so each one runs in O(1) time.

STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · FUNCTIONS & CLASSES

    Rectangle Class in Python, explained

    Problem overview

    A class bundles some values with the questions you can ask about them. Here the values are a rectangle's width and height, and the questions are its area, its perimeter and whether it is a square. You write the class Rectangle with a constructor and three methods: area(), perimeter() and is_square().

    For Rectangle(3, 4) the area is 3 * 4 = 12 and the perimeter is 3 + 4 + 3 + 4 = 14. The sides differ, so it is not a square. For Rectangle(5, 5) the area is 25, the perimeter is 20 and the answer to the square question is True. The lesson's tests print the booleans as True or False.

    Approach: each object keeps its own sizes

    Every rectangle you create needs to remember its own width and height. In Python the constructor is the method __init__, and self is the object being created. Writing self.width = width stores the number on that one object, so a second rectangle gets its own copy and the two never mix.

    The other methods can't see the parameters of __init__: those variables disappear when the constructor ends. They read the sizes back through self, which is why the constructor has to store them as attributes first.

    Step by step

    1. Store the width as self.width inside __init__.
    2. Store the height as self.height on the next line.
    3. area returns the width times the height. A 3 by 4 rectangle is 3 rows of 4 unit squares, 12 in all.
    4. perimeter walks around the rectangle: width, height, width, height. That is twice the sum of the two sizes, so the addition goes in parentheses and the result is multiplied by 2.
    5. is_square returns the comparison of the two sizes with ==. A comparison already produces True or False, so no if is needed.

    The solution in Python

    class Rectangle:
        def __init__(self, width: int, height: int):
            self.width = width
            self.height = height
        def area(self) -> int:
            return self.width * self.height
        def perimeter(self) -> int:
            return 2 * (self.width + self.height)
        def is_square(self) -> bool:
            return self.width == self.height
    

    Creating rectangles and asking them questions looks like this:

    for w, h in [(3, 4), (5, 5), (2, 10), (10, 2)]:
        r = Rectangle(w, h)
        print(w, h, r.area(), r.perimeter(), r.is_square())
    

    It prints:

    3 4 12 14 False
    5 5 25 20 True
    2 10 20 24 False
    10 2 20 24 False
    

    The last two rectangles are the same shape turned on its side, so the area and perimeter don't change.

    Python details

    • self is the first parameter of every method, but you don't pass it. r.area() hands r to the method as self automatically.
    • The annotations are hints. width: int and -> int document what the code expects. Python doesn't enforce them.
    • Attributes are public. Python has no private fields, so code outside the class can read and change r.width. After a = Rectangle(3, 4) and a.width = 6, a.area() is 24, while another rectangle Rectangle(5, 5) still has area 25.

    Edge cases and common mistakes

    • Forgetting self. in the constructor. A line like width = width only sets a local variable, and the object keeps nothing.
    • Leaving out the parentheses in perimeter. 2 * self.width + self.height doubles only the width. For a 3 by 4 rectangle that gives 10, not 14.
    • Forgetting the parentheses on a call. r.area is the method itself, not its result. Always write r.area().
    • Using an if for is_square. It works, but return self.width == self.height says the same in one line.
    • Complexity. Each method does a fixed amount of arithmetic, so each runs in O(1) time.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free