Python Relationships and Their Types
1. Association
A general relationship where one class uses or interacts with another.
No ownership; both can exist independently.
Example:
class Doctor:
def __init__(self, name):
[Link] = name
class Hospital:
def __init__(self, hospital_name):
self.hospital_name = hospital_name
def assign_doctor(self, doctor):
print(f"{[Link]} is assigned to {self.hospital_name}")
2. Aggregation (Has-A)
A "whole-part" relationship.
One class contains another class, but both can exist independently.
A form of Association with a "has-a" relationship.
Example:
class Engine:
def __init__(self, horsepower):
Python Relationships and Their Types
[Link] = horsepower
class Car:
def __init__(self, model, engine):
[Link] = model
[Link] = engine
3. Composition (Strong Has-A)
A stronger form of Aggregation.
If the container object is destroyed, the contained object is also destroyed.
Tightly bound: the part cannot exist independently.
Example:
class Engine:
def __init__(self, horsepower):
[Link] = horsepower
class Car:
def __init__(self, model, horsepower):
[Link] = model
[Link] = Engine(horsepower)
4. Inheritance (Is-A)
One class (child) inherits the properties and methods of another class (parent).
Python Relationships and Their Types
Describes an "is-a" relationship.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
Summary Table
Relationship Type Example Keywords Dependency Level
Association Uses interacts with Low
Aggregation Has-A contains Medium
Composition Strong Has-A owns completely High
Inheritance Is-A subclass High