Fundamentals 11 min read

Understanding Class Relationships in Object‑Oriented Programming: Dependency, Composition, and Inheritance with Python Examples

This article explains the three core class relationships in object‑oriented programming—dependency, composition, and inheritance—illustrates each with clear Python code, discusses inheritance advantages, single‑ and multiple‑inheritance types, and introduces the method‑resolution‑order (MRO) algorithm.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Class Relationships in Object‑Oriented Programming: Dependency, Composition, and Inheritance with Python Examples

In object‑oriented programming, classes can relate to each other in three fundamental ways: dependency, composition, and inheritance.

Dependency relationship occurs when a class name or object is passed as a parameter to another function. Example:

class People:
    def __init__(self, name):
        self.name = name
    def open(self, bx):
        bx.open_door(self)
    def close(self, bx):
        bx.close_door(self)

class Refrigerator:
    def __init__(self, name):
        self.name = name
    def open_door(self, p):
        print(f"{p.name} 打开冰箱")
    def close_door(self, p):
        print(f"{p.name} 关闭冰箱")

r = People("大魔")
aux = Refrigerator("奥克斯")
r.open(aux)   # aux passed as argument
r.close(aux)

Composition relationship means an object of one class is stored as an attribute of another class. Example:

class Boy:
    def __init__(self, name, g):
        self.name = name
        self.g = g   # g is a Girl instance
    def eat(self):
        print(f"{self.name} 和 {self.g.age} 岁的 {self.g.name} 一起吃饭")
    def make_keep(self):
        self.g.live(f"{self.g.weight}公斤的{self.g.name} 给 {self.name} 踩背")

class Girl:
    def __init__(self, name, age, sex, weight, *args):
        self.name = name
        self.age = age
        self.sex = sex
        self.weight = weight
        self.args = args
    def live(self, argv):
        print(f"直播内容:{argv}")

g = Girl("乔毕得", 54, "女", 220)
b = Boy("太博", g)
b.make_keep()

Inheritance relationship allows a subclass to acquire attributes and methods of a parent class, optionally overriding or extending them. Benefits include reduced code duplication, clearer structure, and better maintainability.

Python supports single inheritance, multiple inheritance, and distinguishes classic classes (pre‑Python 2.2) from new‑style classes (Python 3 and later). Example of a simple inheritance hierarchy:

class Animal:
    live = "活的"
    def __init__(self, name, age, sex):
        print("is __init__")
        self.name = name
        self.age = age
        self.sex = sex
    def eat(self):
        print("吃")

class Human(Animal):
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Pig(Animal):
    pass

Multiple inheritance introduces the Method Resolution Order (MRO) problem. Python uses the C3 linearization algorithm for new‑style classes. The mro() method returns the computed order. Example demonstrating MRO with classic and new‑style classes:

class A:
    name = "小宝"

class B(A):
    name = "太博"

class C(A):
    name = "marry"

class D(B, C):
    name = "魔22"

class H:
    name = "aaa"

class Foo(H, D):
    pass

f = Foo()
print(f.name)   # prints "aaa" according to C3 MRO

The article concludes with a summary of classic‑class depth‑first left‑to‑right lookup versus new‑style class C3 linearization, and provides additional exercises for practicing inheritance, method overriding, and MRO inspection.

PythonOOPDependencyinheritanceMROcompositionClass Relationships
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.