Composition


In programming, when a class is used inside another class, it is referred to as composition or aggregation. This is a way to achieve code reuse and establish relationships between different classes. It’s a fundamental concept in object-oriented programming.

Compared to the inheritance relationship, the composition:

Composition Inheritance
A class is used inside another class A class is created from another class
It’s a has-a relationship It’s a is-a relationship
It’s a part-of relationship It’s a kind-of relationship
It’s a strong relationship It’s a weak relationship
It’s a static relationship It’s a dynamic relationship


How to define and use composition


class Stud:
    def __init__(self, position, is_vertical=True, width=0.2, height=0.5):
        self.position = position
        self.is_vertical = is_vertical
        self.width = width
        self.height = height

class Frame:
    def __init__(self, length=2, studs=None):
        self.length = length
        self.studs = studs or []

    def add_stud(self, stud):
        self.studs.append(stud)

# create the studs
stud_A = Stud((0, 0, 0))
stud_B = Stud((0.5, 0, 0))
stud_C = Stud((1, 0, 0))
stud_D = Stud((0, 0, 0), is_vertical=False)
stud_E = Stud((0, 2, 0), is_vertical=False)

# create the frame
frame = Frame()

# add the studs to the frame
frame.add_stud(stud_A)
frame.add_stud(stud_B)
frame.add_stud(stud_C)
frame.add_stud(stud_D)
frame.add_stud(stud_E)


🛠 Exercise


01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍