Mar-12-2021, 09:57 PM
(This post was last modified: Mar-14-2021, 03:40 AM by Drone4four.
Edit Reason: Correct subject
)
I’m taking a Udemy course by Derek Banas titled, Python Programming Bootcamp. Derek demonstrates the basics of OOP using a script which calculates the area using a height and width value collected from the user (user input). I’ve ventured to re-write Derek’s script using functions and variables instead of methods and attributes. Derek’s script is 52 lines long. Mine is 13 lines long. (Both scripts can be found below.)
My first question for all of you: Is there really a benefit to OOP with all the added complexity required when the same outcome can be achieved with 75% less code?
Here is Derek’s original script:
My first question for all of you: Is there really a benefit to OOP with all the added complexity required when the same outcome can be achieved with 75% less code?
Here is Derek’s original script:
class Square: def __init__(self, height="0", width="0"): self.height = height self.width = width # This is the getter # @property defines that any call to height runs the code in the height method below it @property def height(self): print("Retrieving the height") # Put a __ before this private field return self.__height # This is the setter @height.setter def height(self, value): # We protect the height from receiving a bad value if value.isdigit(): # Put a __ before this private field self.__height = value else: print("Please only enter numbers for height") # This is the getter @property def width(self): print("Retrieving the width") return self.__width # This is the setter @width.setter def width(self, value): if value.isdigit(): self.__width = value else: print("Please only enter numbers for width") def get_area(self): return int(self.__width) * int(self.__height) def main(): square = Square() height = input("Enter height : ") width = input("Enter width : ") square.height = height square.width = width print("Height :", square.height) print("Width :", square.width) print("The Area is :", square.get_area()) main()Here is my script:
width = input("Enter your width: ") height = input("Enter your height: ") def calculate_area(width, height): try: return int(width) * int(height) except ValueError: print("Please enter a digit, not a character") width = input("Enter your width: ") height = input("Enter your height: ") calculate_area(width, height) print(calculate_area(width, height))My second question for all of you: Since the purpose of this script is so basic, it was relatively easy for me to emulate the outcome. But how might you people re-write my script or even Derek’s script to optimize and improve them?