Lesson 12: Object-Oriented Programming Basics

Understanding classes, objects, and the foundations of OOP in Python

What Is Object‑Oriented Programming?

Object‑oriented programming (OOP) is a programming paradigm based on the concept of “objects” — data structures that contain both data (attributes) and behavior (methods). Python supports OOP and uses it extensively in real‑world applications.

Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class.

Defining a Class

class Person:
    pass

Creating an Object

p = Person()
print(p)

Attributes and Methods

Attributes store data, and methods define behavior.

Adding Attributes

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)
print(p.name)   # Alice
print(p.age)    # 30

Adding Methods

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, I'm {self.name}!")

p = Person("Bob")
p.greet()

The __init__ Method

__init__ is a special method that runs automatically when an object is created. It initializes the object’s attributes.

The self Keyword

self refers to the current instance of the class. It must be the first parameter of every method inside a class.

Encapsulation

Encapsulation means bundling data and methods inside a class. Python uses naming conventions to indicate private attributes:

class BankAccount:
    def __init__(self, balance):
        self._balance = balance   # "protected" by convention

Class vs Instance Attributes

Instance attributes belong to each object. Class attributes are shared across all objects.

class Dog:
    species = "Canine"   # class attribute

    def __init__(self, name):
        self.name = name  # instance attribute

d1 = Dog("Rex")
d2 = Dog("Buddy")

print(d1.species)   # Canine
print(d2.species)   # Canine

Why OOP Matters

Next Steps

Now that you understand the basics of OOP, you're ready to explore inheritance and more advanced class features in Lesson 13: Classes, Objects, and Inheritance.

← Back to Lesson Index