Saturday, February 8, 2014

Scope of Names and Variables

This week introduced a familiar topic to me known as the scope of names and variables. The immediate difference that I found between the scope in python and java was that scope in python is separated by indentation and white space. While in java the scope of the variables can be understood through what brackets the variables are within. In my understanding of scope, scope is the boundaries of where the variable and names can be accessed. This is a very important concept to understand because in a large program where multiple variables have the same name due to a limited number of ways to describe the same object, the coder will want to specify where each variable should and can be accessed by the program. As explained in the lectures, scope has multiple levels going from local to non-local and to global. In python, I learned that scope is determined by searching from the most inner scope and working outwards toward the global scope. For example, let us say there is the following program.
x = 5
def num_squared(x):
    x = 4
    return x**2

>>> num_squared(5)
16

As the output shows, the x that is considered first is the one inside the function definition and not the x that is equal to 5 which is in the global scope in this case. If the x that we wanted was not the x in the function header, or the x in the body of the function, another approach would have to be used to force x to refer to the x in the global scope. This is the part where the lecture created some confusion for me because we were analyzing scope where a program forced certain names and variables to be visible at different scopes. I wasn't able to keep track of what was happening all at once, but after listening to some discussion from other students in the class, some of this confusion was reduced. I believe the main reason why the concept was confusing to me was because I didn't jot down my thoughts to keep track of what each part of the scope program was doing. As a result, I missed many important things that was happening and led to my wrong conclusion and false understanding.

For class inheritance, my understanding of the concept was pretty much on the spot. The exercise in the lecture where we predicted which functions was used by class B helped practice my understanding of how inheritance worked and as well in a way helped improve my understanding of scope. This is because both concepts start from the inner and then work towards the outer. In the case of inheritance, a method is first searched for in the child class and then the parent class if and only if the method does not exist in the child class. Overall, I believe this week was a very successful one.
 

No comments:

Post a Comment