Posted on

# Create a class for a point and use the point class to create a rectangle class in Python

Create a class for a point and use the point class to create a rectangle class - Python:

``````
class Point:
"""
Create a class for a point.

Parameters
----------
x : int
The x-coordinate of the point.
y : int
The y-coordinate of the point.

Attributes
----------
x : int
The x-coordinate of the point.
y : int
The y-coordinate of the point.

Methods
-------
distance_from_origin()
Calculate the distance from the origin.
"""

def __init__(self, x, y):
"""
Initialize the point.

Parameters
----------
x : int
The x-coordinate of the point.
y : int
The y-coordinate of the point.
"""

self.x = x
self.y = y

def distance_from_origin(self):
"""
Calculate the distance from the origin.

Returns
-------
float
The distance from the origin.
"""

return (self.x ** 2 + self.y ** 2) ** 0.5

def __str__(self):
"""Return a string representation of the point."""

return "({0}, {1})".format(self.x, self.y)

def __repr__(self):
"""Return a string representation of the point."""

return "Point({0}, {1})".format(self.x, self.y)

def __eq__(self, other):
"""Return True if the points have the same coordinates."""

return (self.x == other.x) and (self.y == other.y)

def __ne__(self, other):
"""Return True if the points have different coordinates."""

return not self == other

def __lt__(self, other):
"""Return True if the point is less than the other point."""

return (self.x < other.x) and (self.y < other.y)

def __le__(self, other):
"""Return True if the point is less than or equal to the other point."""

return (self < other) or (self == other)

def __gt__(self, other):
"""Return True if the point is greater than the other point."""

return not (self <= other)

def __ge__(self, other):
"""Return True if the point is greater than or equal to the other point."""

return not (self < other)

"""Return a new point that is the sum of this point and another."""

return Point(self.x + other.x, self.y + other.y)

def __sub__(self, other):
"""Return a new point that is the difference of this point and another."""

return Point(self.x - other.x, self.y - other.y)

def __mul__(self, scalar):
"""Return a new point that is this point scaled by a scalar."""

return Point(self.x * scalar, self.y * scalar)

def __rmul__(self, scalar):
"""Return a new point that is this point scaled by a scalar."""

return Point(scalar * self.x, scalar * self.y)

def __truediv__(self, scalar):
"""Return a new point that is this point scaled by 1/scalar."""

return Point(self.x / scalar, self.y / scalar)

def __abs__(self):
"""Return the distance from the origin."""

return self.distance_from_origin()

def __neg__(self):
"""Return a new point that has been negated."""

return Point(-self.x, -self.y)
``````