215 Variable scope in OOP
In procedural programming, what are the two main types of variable scope?
Show solution
The two main types are global scope, where variables are available throughout the program, and local scope, where variables exist only within a function and disappear when the function exits.
What is object scope in OOP, and what type of variable has object scope?
Show solution
Object scope refers to variables that are available to all methods of an object — these are called instance variables. They are prefixed with self.# (e.g. self.count) and belong to the object rather than just a single method.
In a method, how can you tell the difference between a local variable and an instance variable?
Show solution
A local variable does not begin with self.# and only exists while the method runs. An instance variable does begin with self.# and is available to all methods of the object.
Compare what happens to local and instance variables after a method exits.
Show solution
When a method exits:
Local variables disappear. They are deleted from memory and can no longer be accessed by any method of the object.
Instance variables (those prefixed with
self.#) remain. They continue to exist as part of the object and can be accessed or modified by other methods of that object.
Given this code, what will
obj.countprint after both increment calls?
Show solution
It will print 2, because self.count starts at 0 and is increased by 1 each time increment() is called.
Write a class called
Counterthat starts with a count of 10 and has a methodaddFive()that adds 5 to the count.
Why can two different
LightSwitchobjects have different values forswitchIsOnat the same time?
Last updated
Was this helpful?