Changes

Jump to: navigation, search

Rchan sandbox

22 bytes added, 13:06, 3 November 2019
Investigation III - Scope
= Investigation III - Scope =
: Scope means where an object can be accessed, and how long that object exists.
: In this investigation, we will look at the types of scope you're most likely to run into and which are most likely to cause trouble for you. We will not be explicitly looking at class scope, nested functions, built-in objects, constants, and mutability.
== Part 1: Local Scope ==
: In Python any object that is created inside a function has local scope. That means that it is accessible only by code inside that function, and is not accessible by any code outside of the function. In other languages this concept is related to '''block''' scope but that does not exist in python. Every block inside a function has the same scope.
: Try the following code. Have each in a separate Python file.
: '''lab7g.py''' - local scope:<source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
==Part 2: Global Scope ==
: Sometimes you want to have an object accessible from anywhere in your program, including inside and outside any functions. Here's an example:
:'''lab7h.py''' - global scope<source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
</source>
: Note that the same thing is printed over and over because the '''schoolName''' object is defined outside a function which makes it global which makes it accessible from anywhere.
: Python has one weird quirk when it comes to global scope: if you assign something to an existing object inside a function - it will assume you want to create a new object in that function's local scope. That will hide the global object inside the function unless you declare it explicitly with the global keyword:: '''lab7i.py''' - global keyword<source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
::Note that the function1() call does not modify the global '''schoolName''' object but function2() does.
: As the last task for this lab: modify the script above so that it would print the following, by changing only the scope of some objects. Save the program as '''lab7i.py''': <source lang="bash">
print() in main on schoolName: Seneca
print() in function1 on schoolName: SICT
== Object/Instance Scope ==
: Every object can have attributes that exist for that object only. You create and access those attribute with the name of the object itself using the dot '.' notation. Note that these may not part of the '''class''' object's attribute. Each object has its own set of '''instance''' attributes. You will have seen that when you created objects in the Classes and Objects section above.
= LAB 7 SIGN-OFF (SHOW INSTRUCTOR) =
1,760
edits

Navigation menu