1
Lesson 1
Introduction to Object-Oriented Programming
Object-Oriented Programming is a way of writing programs by using objects. Think of objects as things in the real world. For example, a car, a dog, or even a smartphone can be objects. Each object has:
- Attributes (things it has): A car has a color, brand, and speed.
- Behaviors (things it does): A car can start, stop, and accelerate.
In Python, we create objects using classes.
Key concepts of OOP
- Class: A blueprint or template for creating objects. For example, the blueprint of a car.
- Object: An instance of a class. For example, your specific car, a red Toyota.
- Attributes: Variables that store information about the object. For example, the car's color is "red".
- Methods: Functions that define behaviors for an object. For example,
makes the car start.start()
- Encapsulation: Bundling the data (attributes) and methods inside a class.
- Inheritance: A way to create a new class from an existing class. For example, a "SportsCar" can inherit from a general "Car" class.
- Polymorphism: Objects can share the same method name but behave differently based on their class.
Let's see an example
Imagine we want to create a program to manage pets:
# Define a class
class Dog:
# Constructor method: Defines how to create a Dog object
def __init__(self, name, age):
self.name = name # Attribute: Dog's name
self.age = age # Attribute: Dog's age
# Method: A behavior of the dog
def bark(self):
return f"{self.name} says Woof!"
def birthday(self):
self.age += 1
return f"{self.name} is now {self.age} years old!"
# Create objects (instances of Dog)
dog1 = Dog("Buddy", 3) # A dog named Buddy, 3 years old
dog2 = Dog("Charlie", 5) # A dog named Charlie, 5 years old
# Access attributes and call methods
print(dog1.name) # Output: Buddy
print(dog1.bark()) # Output: Buddy says Woof!
print(dog1.birthday()) # Output: Buddy is now 4 years old!
Why use OOP?
- Reusability: Create reusable blueprints (classes) and avoid rewriting code.
- Organization: Bundle data and behaviors together, making your program easier to manage.
- Scalability: Easily add new features by extending classes.