Loading...

Python Inheritance

A child class keeps what the parent already stores, and it can replace one job. Desk is a child of Lamp. You write that as Desk(Lamp). The child does not install a package and does not create a folder. Desk("blue") still stores the word blue, because the child did not rewrite init. The parent’s label still puts glow in front of the word. The child’s label puts desk in front of it. You still build each lamp yourself. The line class Desk(Lamp) does not build one for you.

a child replaces one job

python
class Lamp:
    def __init__(self, color):
        self.color = color
    def label(self):
        return "glow " + self.color

class Desk(Lamp):
    def label(self):
        return "desk " + self.color

plain = Lamp("blue")
desk = Desk("blue")
print(plain.label())
print(desk.label())

The screen shows two lines. The first is glow blue. The second is desk blue. plain was built from Lamp, so the parent’s job runs. desk was built from Desk, so the child’s job runs. There is a space in each line, between the front word and blue. Both lamps store the same word. Only the job in front of it changed. print writes the lines. The methods hand the words back.

The child does not rewrite the parent. After this program, a lamp built from Lamp still says glow blue. The red lamp from the previous page is not here. What changed is which job runs for a Desk. plain.color and desk.color are both the word blue. The child did not store a new color. It only replaced label. If the child had no label of its own, the parent’s glow line would run for the desk too. This child does have its own label, so the second line is desk blue.

The next page is special methods. This page only shows a child that keeps the stored word and replaces one job.

A child keeps the word

Desk is a child of Lamp. The screen is glow blue, then desk blue. The stored word stays blue. The child replaces label and does not rewrite the parent. The next page is special methods.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

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

❓
7
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