Loading...

Python Composition

You put one object inside another. The pen stores the word blue. The bag stores that pen, not the word, and the bag does not become a child of the pen. You do not install a package and you do not create a folder. You build the pen first, then you hand that pen to the bag. print(bag.pen.color) writes blue. The bag has no color of its own.

a pen inside a bag

python
class Pen:
    def __init__(self, color):
        self.color = color

class Bag:
    def __init__(self, pen):
        self.pen = pen

pen = Pen("blue")
bag = Bag(pen)
print(bag.pen.color)

The screen shows one word: blue. pen.color and bag.pen.color are that same word, because bag.pen is the pen you built. print writes it. There is no second line. The word badge is not added, and the number 4 is not written. The line class Bag does not put a pen inside anything. Bag(pen) is what stores the pen. init on the bag runs at that moment, and self is the bag.

The color sits on the pen. bag.color is not in this program. That read would stop, and the name of the stop is AttributeError, because the bag has no color stored on it. None is not written, and the program does not go on. You also do not hand the bag the bare word blue. Bag("blue") is not in the program. A word has no color of its own, so reading .color there would stop with the same name, AttributeError. This page does not write class Bag(Pen). That form would make a child class. Here the pen sits inside the bag.

📊 The pen, the bag, the word

What you have What it is
pen the pen you built, storing blue
bag.pen that same pen, held inside the bag
bag.pen.color the word blue

The next page is a class that mainly stores fields. This page only puts a pen inside a bag and reads the stored word through the bag.

The pen sits inside the bag

The screen is blue. The bag holds the pen, and the word lives on the pen. The bag is not a child of the pen. The next page is a class that mainly stores fields.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

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

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