Adding/subtracting angles

Lets say we have a 360 degree wheel. Is there a way in python to alter the subtraction and addition so that you can do stuff like :

range = 0 , 360
360 +2 = 2

90 + 360 = 90

etc

2 Likes

Sure. Use the modulo (“remainder”) operator, %

print((360 + 90) % 360)

Output:

90
2 Likes

To implement customized behaviors for operators, consider creating a class that includes dunder methods, such as the following:

class Angle:
  def __init__(self, degrees):
    self.degrees = degrees % 360
  def __repr__(self):
    return "{}°".format(self.degrees) 
  def __add__(self, other):
    return Angle(self.degrees + other.degrees)
  def __sub__(self, other):
    return Angle(self.degrees - other.degrees)

angle_a = Angle(270)
angle_b = Angle(120)
angle_c = angle_a + angle_b
angle_d = angle_b - angle_a
print(angle_a)
print(angle_b)
print(angle_c)
print(angle_d)

Output:

270°
120°
30°
210°
4 Likes

One could additionally let it play nice with other numbers:

Angle(0) + 360
360 + Angle(0)

The former involves testing the types (there might be some abstract Number that numbers identify as) or try/except, the latter needs alternative dunder methods __rsub__, __rmul__ etc which are called when the left side fails to handle the operation

>>> import numbers
>>> help(numbers.Number)
Help on class Number in module numbers:

class Number(builtins.object)
 |  All numbers inherit from this class.
...
>>> isinstance(5, numbers.Number)
True

It could be argued that repr should return a string which can be evaluated to get the value back, while str can be used for “pretty” string conversion

2 Likes