216 Calling methods
What is the generic syntax for calling a method on an object in Python?
Why must the class definition appear before any code that creates objects from it?
Show solution
Because Python needs to know what the class is (its structure and methods) before it can create objects (instances) from it. If the class were undefined at the time of instantiation, Python would raise an error.
What happens to
oLightSwitch1.switchIsOnandoLightSwitch2.switchIsOnin the following code?
oLightSwitch1 = LightSwitch()
oLightSwitch2 = LightSwitch()
oLightSwitch1.turnOn()
oLightSwitch1.show()
oLightSwitch2.show()Show solution
oLightSwitch1.switchIsOn becomes True after turnOn() is called, so oLightSwitch1.show() prints True. oLightSwitch2.switchIsOn remains False, so oLightSwitch2.show() prints False.
How does the use of instance variables in the
LightSwitchclass help when working with multiple objects?
Show solution
Each object (instance) has its own separate copy of the instance variables (like switchIsOn). This means the state of one object does not affect the state of another, making the program easier to manage and scale.
Write Python code to create two
LightSwitchobjects. Turn the first one on and leave the second one off. Print the state of both switches.
Why is it better to use objects with instance variables instead of using multiple global variables in larger projects?
Last updated
Was this helpful?