← Back to Python Course | Chapter 7: OOP | Lesson 1 of 11

Python OOP Introduction

What is OOP?

Object-Oriented Programming organizes code around objects that bundle data and behavior together, rather than passing data between standalone functions -- this mirrors how real-world things work (a car has both properties like color and actions like drive()) and keeps related logic in one place as programs grow.

Example: What is OOP?

python
class Car:
    color = "red"
    def drive(self):
        print("Driving")

Car().drive()

Objects and Classes

A class is the blueprint -- it defines what attributes and methods every object of that type will have -- while an object is one concrete instance built from that blueprint, holding its own actual values (two Car objects share the class definition but have different colors).

Example: Objects and Classes

python
class Car:
    def __init__(self, color):
        self.color = color

car1 = Car("red")
car2 = Car("blue")
print(car1.color, car2.color)

Encapsulation

Encapsulation keeps an object's internal data bundled with the methods that operate on it and limits direct outside access -- in Python this is a convention rather than an enforced rule, signaled by prefixing attribute names with an underscore or double underscore.

Example: Encapsulation

python
class Account:
    def __init__(self, balance):
        self._balance = balance  # underscore signals "internal use"

print(Account(100)._balance)

Abstraction

Abstraction means exposing only what a user of your class needs to know (like a .drive() method) while hiding the messy implementation details behind it (engine RPM calculations, gear ratios) -- it lets you change the internals later without breaking code that uses the class.

Example: Abstraction

python
class Car:
    def drive(self):
        print("Engine details are hidden from the caller")

Car().drive()

Benefits of OOP

Because classes can be extended and reused across a codebase instead of copy-pasted, OOP tends to produce more modular code -- fixing a bug or adding a feature in one base class automatically benefits every class that inherits from it.

Example: Benefits of OOP

python
class Animal:
    def eat(self):
        print("Eating")

class Dog(Animal):
    pass

Dog().eat()  # inherited automatically

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.