🧱 Python Course in 4 to 6 Weeks – Lesson 14: OOP Basics – Classes & Objects
Welcome to Lesson 14 of the Python Course in 4 to 6 Weeks! Today, we’ll dive into Object-Oriented Programming (OOP), a powerful paradigm that helps you build structured and scalable applications in Python.
🔍 What is OOP?
OOP stands for Object-Oriented Programming. It’s a method of programming where you design code using objects and classes. It’s widely used in real-world applications such as games, GUI programs, and web development.
📦 Key Concepts of OOP
- Class – A blueprint for creating objects
- Object – An instance of a class
- Attributes – Variables that hold data inside a class
- Methods – Functions that belong to a class
- Constructor – The
__init__()
method used to initialize object properties - Inheritance – One class can inherit features from another class
🧪 Example 1: Creating a Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, I'm {self.name} and I'm {self.age} years old.")
# Creating an object
person1 = Person("Amr", 25)
person1.greet()
🧬 Inheritance Example
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def show_id(self):
print(f"My student ID is {self.student_id}.")
student1 = Student("Sara", 21, "S101")
student1.greet()
student1.show_id()
⚠️ Common Mistakes
- ❌ Forgetting
self
as the first parameter in class methods - ❌ Not using
super()
when inheriting from a parent class - ❌ Confusing class-level vs. instance-level variables
🎯 Practice Challenge
Create a class Car
with attributes: brand
, model
, year
. Then:
- Add a method to display full info
- Create a subclass
ElectricCar
that addsbattery_size
- Override the info method to include battery size
📥 Tools You'll Need
- 🐍 Python: https://www.python.org/downloads/
- 📝 VS Code: https://code.visualstudio.com/
- 🌐 Replit: https://replit.com/languages/python3
📌 Final Words
OOP is essential for writing clean and maintainable Python programs. Once you master classes, objects, and inheritance, you're ready to move on to real-world applications and frameworks.
🔗 Coming Next:
Lesson 15: Real-World Python – Web, Data, Automation 🌍