Python Methods
A method is a job that belongs to one lamp. lamp.label() runs that job and hands back the words glow blue. The parentheses are part of running it. Without them you have not run the job, and the screen is not glow blue. label uses the word already stored on that lamp. It does not install a package, and it does not create a folder. The indented lines under label are the job. return hands the words back. It does not write them on the screen by itself.
class Lamp:
def __init__(self, color):
self.color = color
def label(self):
return "glow " + self.color
lamp = Lamp("blue")
print(lamp.label())
The screen shows glow blue. There is a space between glow and blue. label built those words from the stored color and handed them back. print is what writes them. If the print line were missing, the method would still hand the words back and the screen would stay empty. lamp.color is still the stored word blue. lamp.label() is the job that puts glow in front of it. They are not the same reading.
class Lamp:
def __init__(self, color):
self.color = color
def label(self):
return "glow " + self.color
one = Lamp("blue")
two = Lamp("red")
print(one.label())
print(two.label())
The screen shows two lines. The first is glow blue. The second is glow red. one and two are two lamps. Each label reads only the word stored on that lamp. Building the red lamp does not change the blue one. one.label() stays glow blue. The pattern Lamp is still the pattern. one and two are the objects. The method is the same job, with a different stored word each time.
Lamp.label() with no lamp is not in either program. The pattern has no stored color of its own, and the job needs a lamp to read. That line stops, and the name of the stop is TypeError. None is not written, and the program does not go on. You build a lamp first, then you write the parentheses on that lamp.
The next page is a child class. This page only runs one job on a lamp, then shows that a second lamp keeps its own words.
A job on the lamp
lamp.label() shows glow blue. print writes the words. The method hands them back. A second lamp can show glow red without changing the first. Lamp.label() with no lamp stops as TypeError. The next page is a child class.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top