Object-Oriented Programming (OOP) is a style of programming based on objects. This might lead you to ask "what are objects?" and that's a good question! An object could be a variable, a data structure such as a list, or even a function.
You might be thinking that sounds fine and dandy, but there's no reason for you to bother with OOP because your coding style right now works great. I'm going to attempt to change your mind by telling you about an example I learned in class.
Let's say you wanted to create a program that worked with different shapes, such as circles, squares, and triangles. These are all different shapes, but they have similar properties because they are shapes. For examples, these shapes would all have a position (x, y). To move a shape, you'll make a function to move the shape. We'll call this function move_to, which will move the shape to a new position (x, y). It happens to be the case that all shapes can be moved with this function. Thus it makes sense to group these shapes by creating a class, called Shape, so that each Shape created as a subclass (e.g. Circle, Square, Triangle) will have access to the function move_to which has become a method in the class Shape. Isn't it amazing how this prevented you from rewriting the same code?
But you might say that you will have a problem now because these shapes can't use the same formula to calculate area, and that's right. What we can do is create a method in Shape called get_area and put the following in the method's body: raise NotImplementedError('Need a subclass')
"Well that seems stupid", is what I initially thought when I first heard of a NotImplementedError in class. I learned minutes later that it is actually extremely useful. We put a NotImplementedError here because there is no one way to calculate the area of all Shapes. So this error tells the client that there is a subclass (e.g. Circle) that knows how to calculate the area. In a subclass such as Square, we would create a method named get_area that calculates the area of a Square. "But how can you do that when you already have a get_area method in Shape?" is something you might be wondering. By rewriting the method get_area in Square, we have overridden the get_area method in Shape. When Square is asked to calculate its area, the get_area method in Square will be called instead of the get_area in Shape. This is because the method is looked for locally first before it is searched for in the parent class.
As you can see, with OOP you can use inheritance to create classes with similar properties to a parent class and you can override methods from the parent class to something different in a subclass. It might be more work than what you're used to, but the end result is definitely worth it as it will save you time and make your code less redundant and more structured.
No comments:
Post a Comment