Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/python/classes.txt

2.0 KiB, 1 run

created by r1870400018:12024, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1from abc import ABC, abstractmethod
2from dataclasses import dataclass, field
3from typing import List, Optional
4
5
6@dataclass
7class Point:
8 x: float
9 y: float
10
11 def distance_to(self, other: 'Point') -> float:
12 dx = self.x - other.x
13 dy = self.y - other.y
14 return (dx ** 2 + dy ** 2) ** 0.5
15
16 def __add__(self, other: 'Point') -> 'Point':
17 return Point(self.x + other.x, self.y + other.y)
18
19
20class Shape(ABC):
21 @abstractmethod
22 def area(self) -> float:
23 pass
24
25 @abstractmethod
26 def perimeter(self) -> float:
27 pass
28
29
30@dataclass
31class Circle(Shape):
32 centre: Point
33 radius: float
34
35 def area(self) -> float:
36 return 3.14159265 * self.radius ** 2
37
38 def perimeter(self) -> float:
39 return 2 * 3.14159265 * self.radius
40
41
42@dataclass
43class Polygon(Shape):
44 vertices: List[Point] = field(default_factory=list)
45
46 def area(self) -> float:
47 n = len(self.vertices)
48 if n < 3:
49 return 0.0
50 total = 0.0
51 for i in range(n):
52 j = (i + 1) % n
53 total += self.vertices[i].x * self.vertices[j].y
54 total -= self.vertices[j].x * self.vertices[i].y
55 return abs(total) / 2.0
56
57 def perimeter(self) -> float:
58 n = len(self.vertices)
59 total = 0.0
60 for i in range(n):
61 j = (i + 1) % n
62 total += self.vertices[i].distance_to(self.vertices[j])
63 return total
64
65
66class Rectangle(Polygon):
67 def __init__(self, origin: Point, width: float, height: float):
68 super().__init__([
69 origin,
70 Point(origin.x + width, origin.y),
71 Point(origin.x + width, origin.y + height),
72 Point(origin.x, origin.y + height),
73 ])
74 self.width = width
75 self.height = height
76
77
78if __name__ == '__main__':
79 rect = Rectangle(Point(0, 0), 4, 3)
80 print(f"area: {rect.area()}")
81 print(f"perimeter: {rect.perimeter()}")
82
83 circ = Circle(Point(0, 0), 5.0)
84 print(f"circle area: {circ.area():.2f}")