Python Class Challenge
Code a Python class named “submarine” to control the navigation of a submarine.
- Create an attribute named “depth” that saves the current meters under water of the submarine. Use a property to set the depth attribute and make it hidden.
- Add a method named “rise” to ascend to a passed depth change.
- Add an attribute named “rise_count” that saves the number of ascents the submarine has done.
- Add a method named “course” that returns the submarine current depth.
- Add a method named “dive” that makes the submarine to sink to a passed depth change.
Steps
- Define the
Submarineclass with the required attributes and methods. - Use a property to hide the
depthattribute and create getter and setter methods for it. - Implement the
"rise"method to ascend the submarine to a passed depth change. - Include an attribute named
rise_countto save the number of ascents. - Create a method named
"course"that returns the submarine’s current depth. - Implement the
"dive"method to make the submarine sink to a passed depth change.
See here for more practice on OOP.
Expected output
Source code
class Submarine:
def __init__(self):
self._depth = 0 # Attribute to store the depth (meters) of the submarine
self.rise_count = 0 # Attribute to save the number of ascents
@property
def depth(self):
return self._depth
@depth.setter
def depth(self, new_depth):
self._depth = new_depth
def rise(self, depth_change):
self._depth -= depth_change
self.rise_count += 1
def course(self):
return self._depth
def dive(self, depth_change):
self._depth += depth_change