Object-Oriented Programming
Classes, objects, inheritance, and encapsulation
What is OOP?
Object-Oriented Programming (OOP) is a way of organizing code by bundling data and behavior into reusable blueprints called classes.
Think of a class like a cookie cutter — it defines the shape, and each cookie you make is an object (an instance of that class).
Why OOP?
- Organize complex programs into logical pieces
- Reuse code through inheritance
- Encapsulate data — keep related variables and functions together
Your First Class
Creating a Class and Objects
Breakdown:
class Dog:— defines a new class namedDog__init__(self, name, age)— the constructor, runs when you create an objectself— refers to the specific instance being created or usedself.name = name— stores the parameter as an instance attribute
Check Your Understanding
What is the purpose of the __init__ method?
Instance Methods
Methods are functions that belong to a class. They always take self as their first parameter:
A BankAccount Class
Inheritance
Classes can inherit from other classes — getting all their methods and attributes for free:
Inheritance Hierarchy
CatandFishinherit fromAnimal- They override the
speak()method with their own version - They can add their own unique methods (like
purr()andswim())
Check Your Understanding
What happens when a child class defines a method with the same name as the parent class?
Class Variables vs Instance Variables
Class vs Instance Variables
- Class variables are shared across all instances — change once, affects everyone
- Instance variables (with
self.) are unique to each object
Exercise
Create a `Rectangle` class with a constructor that takes `width` and `height`. Add a method `area()` that returns `width * height`, and a method `perimeter()` that returns `2 * (width + height)`. Create a rectangle with width 5 and height 3, then print its area and perimeter.
Key Takeaways
- A class is a blueprint for creating objects
- The
__init__method initializes new objects - self refers to the current instance
- Inheritance lets child classes reuse parent code
- Class variables are shared; instance variables are unique
- Method overriding lets child classes customize inherited behavior
OOP is the foundation of almost every large Python project. Understanding classes sets you up to read and write professional-grade code!