-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
42 lines (32 loc) · 1.15 KB
/
classes.py
File metadata and controls
42 lines (32 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Classes — basic OOP in Python.
#
# Demonstrates __init__, instance methods, __str__, and __eq__.
#
# The Line class represents a line segment between two points.
# - __init__ : initialises the object's attributes
# - length() : computes the Euclidean distance between the two points
# - __str__ : controls how the object is printed
# - __eq__ : controls how two objects are compared with ==
from math import sqrt
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def length(self):
return sqrt((self.x2 - self.x1) ** 2 + (self.y2 - self.y1) ** 2)
def __str__(self):
return f'Line({self.x1}, {self.y1}) -> ({self.x2}, {self.y2})'
def __eq__(self, other):
if isinstance(other, Line):
return (self.x1 == other.x1 and self.y1 == other.y1 and
self.x2 == other.x2 and self.y2 == other.y2)
return False
line1 = Line(0, 0, 10, 10)
line2 = Line(0, 0, 20, 10)
line3 = Line(0, 0, 10, 10)
print(line1)
print(f'Length: {line1.length():.4f}')
print(line1 == line2) # False
print(line1 == line3) # True