214 Creating objects from a class
In Python, a class is code that defines what an object will remember (its data or state) and what it will be able to do (its functions or behaviour). Creating an object from a class is instantiation.
class 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 is used here to distinguish between the class name and the object name
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()Creating multiple instances of the same class
Review questions
Last updated
Was this helpful?