Python Practice › OOP Programs › Program 21
Access five classes through one object
Create 5 classes and access them through a single class object (composition).
Output
CPU: 8 cores RAM: 16 GB Disk: 512 GB SSD GPU: integrated Screen: 15.6 inch
Approach
- One
Computerobject holds an instance of each part class.
Solution
class CPU: def info(self): return "CPU: 8 cores"class RAM: def info(self): return "RAM: 16 GB"class Disk: def info(self): return "Disk: 512 GB SSD"class GPU: def info(self): return "GPU: integrated"class Screen: def info(self): return "Screen: 15.6 inch" class Computer: def __init__(self): self.parts = [CPU(), RAM(), Disk(), GPU(), Screen()] def specs(self): return [p.info() for p in self.parts] for line in Computer().specs(): print(line)Output
CPU: 8 cores RAM: 16 GB Disk: 512 GB SSD GPU: integrated Screen: 15.6 inch
Line by line
Lines 12-14
The Computer “has” five parts; this is composition rather than inheritance.
Learn the concept
New to this topic? Read the lesson, then come back.