Created
August 19, 2020 10:22
-
-
Save staffordsmith83/0fb7b1b4b573def974ddad08026c741a to your computer and use it in GitHub Desktop.
Bearing Class, stores a bearing in degrees. Has a method to return the bearing in DMS format!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bearing: | |
"""Class with one variable - angle. Intended to store bearings in degrees. | |
Values must be between 0 and 360 inclusive. Included methods - dd2dms(object). | |
Will return the degrees minutes seconds value of the bearing stored in the object. | |
Syntax - Bearing.dd2dms(my_bearing)""" | |
def __init__(self, angle=360): | |
# underscore(_) is used to denote private members | |
self._angle = angle | |
# This is the getter. Use: my_bearing.angle | |
@property | |
def angle(self): | |
return self._angle | |
# This the setter. Use: my_bearing.angle = 33 | |
# Demands input to be a number (integer or float) between 0 and 360 inclusive. | |
@angle.setter | |
def angle(self, angle): | |
try: | |
if float(angle) >= 0 and float(angle) <= 360: | |
print("Yes input string is a number between 0 and 360 inclusive.") | |
print("Writing value to Bearing object...") | |
self._angle = angle | |
else: | |
print("That's not a number between 0 and 360") | |
print("No changes made.") | |
except IOError as error_details: | |
print(error_details, '\nIOError, No changes made.\n') | |
except ValueError as error_details: | |
print(error_details, '\nValueError, No changes made.\n') | |
except TypeError as error_details: | |
print(error_details, '\nTypeError, No changes made.\n') | |
# This prints the output nicely | |
# Use: print(my_bearing) | |
def __repr__(self): | |
return 'Bearing({})'.format(self._angle) | |
# This is the equals method, returns true if the objects | |
# have equal values in each member. | |
def __eq__(self, other): | |
return self._angle == other.angle | |
# Converts bearing from decimal degrees (DD) to degrees minutes seconds (DMS) | |
# and returns a formatted answer. | |
def dd2dms(self): | |
dd = self._angle | |
is_positive = dd >= 0 | |
dd = abs(dd) | |
minutes, seconds = divmod(dd * 3600, 60) | |
degrees, minutes = divmod(minutes, 60) | |
degrees = degrees if is_positive else -degrees | |
# the next line formats the returned value for display | |
return str(int(degrees)) + u"\u00b0" + str(int(minutes)) + "'" + str(format(seconds, '.1f')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment