Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Is Object-Oriented Programming?
  • - Classes and Objects
  • - Adding Attributes and Methods
  • - The self Keyword
  • - Example: Bank Account Class
  • - Why Use OOP?
  • - Mini Project Step

13. Introduction to Object-Oriented Programming (OOP)

Level: IntermediateDuration: 30m

What Is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming style that organizes code into reusable structures called **objects**. These objects are created from **classes** and are used to model real-world things like users, cars, or bank accounts.

  • OOP makes code reusable
  • Improves readability and structure
  • Helps organize larger projects

Classes and Objects

A **class** is a blueprint. An **object** is something built from that blueprint. Example: a class could be 'Dog', and objects are 'German Shepherd', 'Bulldog', etc.

python
class Dog:
    pass

my_dog = Dog()
print(type(my_dog))

Adding Attributes and Methods

Attributes are variables inside a class, and methods are functions that belong to a class.

python
class Dog:
    def __init__(self, name, breed):  # Constructor
        self.name = name
        self.breed = breed

    def bark(self):  # Method
        return f"{self.name} says woof!"

my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.bark())
💡 `__init__` is called automatically when you create an object. It's used to initialize attributes.

The self Keyword

`self` refers to the current object being created or used. It allows access to attributes and methods inside a class.

Example: Bank Account Class

python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return f"New balance: ${self.balance}"

account = BankAccount("Sarah", 1000)
print(account.deposit(500))

Why Use OOP?

  • Keeps code organized
  • Encourages reusability
  • Makes large projects easier to manage
  • Helps model real-world concepts

Python Classes Documentation

Mini Project Step

Create a class called `Calculator` that has methods for adding, subtracting, multiplying, and dividing two numbers. This will begin converting your procedural calculator into an object-oriented one.