Search⌘ K

Solution Review: Implement Rectangle Class Using Encapsulation

Understand how to implement a Rectangle class in Python using encapsulation. Learn to define private properties and create methods to calculate area and perimeter, ensuring data hiding and better class design.

We'll cover the following...

Solution #

Python 3.5
class Rectangle:
def __init__(self, length, width):
self.__length = length
self.__width = width
def area(self):
return (self.__length * self.__width)
def perimeter(self):
return (2 * (self.__length + self.__width))
obj1 = Rectangle(4, 5)
print("Area is", obj1.area())
print("Perimeter is", obj1.perimeter())

Explanation

  1. In lines 3 - 4, we defined the initializer for the class and declared private properties – __length and __width – in it.

  2. In line 7 ...