Python Class Challenge

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

  1. Define the Submarine class with the required attributes and methods.
  2. Use a property to hide the depth attribute and create getter and setter methods for it.
  3. Implement the "rise" method to ascend the submarine to a passed depth change.
  4. Include an attribute named rise_count to save the number of ascents.
  5. Create a method named "course" that returns the submarine’s current depth.
  6. Implement the "dive" method to make the submarine sink to a passed depth change.

See here for more practice on OOP.

Expected output

python class problem with solutions

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

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart