Sunday, February 8, 2015

Week 5: Inheritance and Recursion in Python


Inheritance
                Inheritance is a powerful tool that allows a programmer to organize their code. When defining a new class, every method from parent classes are inherited. By default, every class in Python is a subclass of type object and inherits its methods. The Python constructor __init__ initializes the new object and is called every time an instance of a class is created. If a method exists in both the parent class and the child class, the most specific method is the one that will be called. For example, say that parent class called Ball has a child class called BaseBall that also both have methods called bounce. Which bounce will be called if you call method bounce on a BaseBall? Logically, the method bounce in class BaseBall would be called. If you create a Ball and call bounce on it, since Ball is not a type of BaseBall, its most specific method is in class Ball and that is the one that will be called.

Recursion
                We have just started to learn about recursion. Recursion can simplify certain problems that would be more difficult to do without it. The basic idea of recursion is that it breaks down a hard problem into smaller, simpler steps that are easier to solve. The simplest step is called the base case.
Tracing recursion can be quite difficult if inductive reasoning is not used. When a problem requires the function to call itself many times, it can become difficult and time consuming follow all of the steps the computer is taking. Using inductive reasoning, we start with the simplest case (base case) and trace it fully to prove that it will always be true. Every time we increase the difficulty a little, we can skip the steps that we previously proved so we can arrive at the answer faster. This is a very powerful concept because it allows a programmer to think about their code at a higher level, and not have to look at every detail.

No comments:

Post a Comment