214 Creating objects from a class
What does the term instantiation mean in object-oriented programming?
Show solution
Instantiation is the process of creating an object (or instance) from a class. It involves using the class as a blueprint to create a working object that has its own data and can perform behaviours defined in the class.
In the LightSwitch example, what does
oLightSwitch = LightSwitch()do?
Show solution
This statement creates a new LightSwitch object (an instance of the LightSwitch class) and assigns it to the variable oLightSwitch.
Explain the difference between a class and an object using the
LightSwitchexample.
Show solution
The LightSwitch class defines what data (state) and behaviours (methods) a light switch will have. An object, like oLightSwitch, is a specific instance of the class that contains its own data and can perform the behaviours defined by the class.
Write a Python line of code that creates a third LightSwitch object called
oLightSwitch3.
If
oLightSwitch1andoLightSwitch2are both instances of LightSwitch, what happens tooLightSwitch2.switchIsOnwhen you calloLightSwitch1.turnOn()?
Show solution
Nothing happens to oLightSwitch2.switchIsOn. Each object has its own copy of switchIsOn, so calling turnOn() on oLightSwitch1 only affects its own switchIsOn value.
Look at this code and predict what will be printed:
Show solution
The output will be:
oLightSwitch1 was turned on, so its switchIsOn is True. oLightSwitch2 was not turned on, so its switchIsOn remains False.
Write a short code snippet that creates two
LightSwitchobjects, turns one on, and prints the state of both.
Last updated
Was this helpful?