""" Ex. 9.6 from "A primer on..." Extend a class for a point in 2D with a subclass that represents the point both in Cartesian and polar coordinates. """ from math import cos, sin, sqrt, pi class Point: def __init__(self, x, y): self.x, self.y = x, y def __str__(self): return f'({self.x:g}, {self.y:g})' class PolarPoint(Point): def __init__(self, r, theta): self.r = r self.theta = theta x = r * cos(theta) y = r * sin(theta) super().__init__(x,y) def __str__(self): cart = super().__str__() polar = f'({self.r:g}, {self.theta:g})' return f'Cartesian: {cart}, polar: {polar}' def test_PolarPoint(): """ r,theta = (1,pi/2) -> x,y = (0,1) r,theta = (2,pi/4) -> x,y = (sqrt(2),sqrt(2)) """ tol = 1e-10 points_polar = [(1,pi/2),(2,pi/4)] points_cart = [(0,1),(sqrt(2),sqrt(2))] for p, x in zip(points_polar,points_cart): pp = PolarPoint(p[0],p[1]) assert abs(pp.r-p[0]) < tol assert abs(pp.theta-p[1]) < tol assert abs(pp.x-x[0]) < tol assert abs(pp.y-x[1]) < tol if __name__ == "__main__": test_PolarPoint() p = Point(1.0, 2.5) print(p) p2 = PolarPoint(1.0, 0.5) print(p2) """ Terminal> python PolarPoint.py (1, 2.5) Cartesian: (0.877583, 0.479426), polar: (1, 0.5) """