Loading...

Python Classes

A class is the pattern for one kind of thing. Lamp is that pattern. Lamp("blue") builds one lamp from it and stores the word blue on that lamp. The class line does not print. You still write print to see the stored word. This page does not install a package, and it does not create a folder. The indented lines under the class are the pattern's inside. self is the lamp being built. self.color = color keeps the word you passed.

one lamp

python
class Lamp:
    def __init__(self, color):
        self.color = color
lamp = Lamp("blue")
print(lamp.color)

The screen shows blue. lamp is the one lamp you built. lamp.color is the word stored on it. Lamp, with a capital L, is the pattern. lamp, with a small l, is the object. They are not the same name. init runs when you write Lamp("blue"). Nothing on this screen is a folder name, and nothing here is a number from a die.

📊 Pattern, object, stored word

Name What it is
Lamp the pattern
lamp one lamp built from that pattern
lamp.color the word blue stored on that lamp

print(Lamp.color) is not in this program. The pattern itself has no color stored on it. That line stops, and the name of the stop is AttributeError. None is not written, and the program does not go on. You build a lamp first, then you read lamp.color. A second lamp, built with another word, would keep its own word. This lamp's blue would not change. That second lamp is not in the program.

The next page is methods. This page only builds one lamp and reads the word stored on it. The lamp does not yet do a job of its own.

One pattern, one lamp

Lamp is the pattern. lamp is one lamp. lamp.color shows blue. Lamp.color stops as AttributeError, because the pattern has no color of its own. The next page is methods.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 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