-
Notifications
You must be signed in to change notification settings - Fork 0
/
degree.py
75 lines (58 loc) · 2.56 KB
/
degree.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import Optional, Union
class Degree(int):
"""
The Degree class is a subclass of int that represents an angle in degrees. It ensures that the angle value is between 0 and 359.
Attributes:
No additional attributes.
Methods:
- __new__(cls, value): Returns a new instance of the Degree class with the specified value.
- __add__(self, other): Overrides the addition operator to perform addition with an integer or another Degree object.
- __sub__(self, other): Overrides the subtraction operator to perform subtraction with an integer or another Degree object.
- __mul__(self, other): Overrides the multiplication operator to perform multiplication with an integer or another Degree object.
- __truediv__(self, other): Overrides the division operator to perform division with an integer or another Degree object.
Example Usage:
# create a Degree object with a value of 45
degree = Degree(45)
# perform addition with an integer
result = degree + 10
print(result) # Output: 55
# perform subtraction with another Degree object
result = degree - Degree(20)
print(result) # Output: 25
# perform multiplication with an integer
result = degree * 2
print(result) # Output: 90
# perform division with an integer
result = degree / 3
print(result) # Output: 15
# ensure that the angle value is always between 0 and 359
result = degree + 400
print(result) # Output: 85
result = degree - 100
print(result) # Output: 305
"""
def __new__(cls, value: Optional[Union[int, float]]):
if value is None:
return None
if type(value) is float:
value=round(value)
value %= 360.0
if not 0 <= value <= 359:
raise ValueError("Value must be between 0 and 359")
return int.__new__(cls, value)
def __add__(self, other: int) -> Optional['Degree']:
if other is None:
return None
return Degree((int(self) + other) % 360)
def __sub__(self, other: int) -> Optional['Degree']:
if other is None:
return None
return Degree((int(self) - other) % 360)
def __mul__(self, other: int) -> Optional['Degree']:
if other is None:
return None
return Degree((int(self) * other) % 360)
def __truediv__(self, other: int) -> Optional['Degree']:
if other is None:
return None
return Degree((int(self) // other) % 360)