215 Variable scope in OOP
Object-oriented programming and classes introduce a third level of scope, typically called object scope, though sometimes referred to as class scope.
class MyClass():
def __init__(self):
self.count = 0 # create self.count and set it to 0
def increment(self):
self.count = self.count + 1 # increment the variableclass LightSwitch():
def __init__(self):
self.switchIsOn = False
def turnOn(self):
# turn the switch on
self.switchIsOn = True
def turnOff(self):
# turn the switch off
self.switchIsOn = False
def show(self): # added for testing
print(self.switchIsOn)
# Main code
oLightSwitch = LightSwitch() # create a LightSwitch object
# Calls to methods
oLightSwitch.show() # call the show method of oLightSwitch
oLightSwitch.turnOn() # call the turnOn method of oLightSwitch
oLightSwitch.show()
oLightSwitch.turnOff() # call the turnOff method of oLightSwitch
oLightSwitch.show()
oLightSwitch.turnOn() # call the turnOn method of oLightSwitch
oLightSwitch.show()Comparing Functions and Methods
Review questions
Last updated
Was this helpful?