v9.1.1
Menu

Basic Class Creation

easyFREEClasses & ObjectsPython OOPPython Foundations

Problem Statement

Create a class to represent a 2D point.

Background

Python classes define objects with:

  • init: Constructor
  • Instance methods: Take self as first argument
  • str: String representation
  • repr: Developer representation

Your Task

Create a class Point with:

  • Constructor taking x and y coordinates
  • Method distance_to(other) returning Euclidean distance to another Point
  • Method translate(dx, dy) that moves the point and returns self
  • str returning "Point(x, y)"

Example

Input
Point(0, 0).distance_to(Point(3, 4))
Output
5.0
Reasoning
  • The input builds two points in the plane: Point(0, 0) is the origin and Point(3, 4) sits 3 units right and 4 units up. distance_to asks for the straight-line distance from the first to other.
  • Per-axis gaps: Δx=3−0=3\Delta x = 3 - 0 = 3 and Δy=4−0=4\Delta y = 4 - 0 = 4. They are the legs of a right triangle whose hypotenuse joins the points.
  • Euclidean distance is that hypotenuse: d=Δx2+Δy2=9+16=25=5d = \sqrt{\Delta x^2 + \Delta y^2} = \sqrt{9 + 16} = \sqrt{25} = 5.
  • The output is 5.0, a real number rather than the integer 5, since a square root is real-valued even when whole.
  • Notice the direction doesn't matter: squaring removes the sign, so the distance from (3,4)(3, 4) back to (0,0)(0, 0) is also 5.0. Likewise (1,2)(1, 2) to (4,6)(4, 6) has legs 3 and 4, giving 5.0 again.
  • Translating shifts both coordinates: (0,0)(0, 0) moved by dx=1dx = 1, dy=2dy = 2 becomes (0+1,0+2)=(1,2)(0 + 1, 0 + 2) = (1, 2). The point itself moves.

Constraints

  • Distance uses Euclidean formula: sqrt((x2-x1)^2 + (y2-y1)^2)
  • translate modifies the point in place and returns self

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.