Object-Oriented Programming

30 min In Progress

Learning Objectives

  • Define classes and create objects
  • Use __init__ and self
  • Understand inheritance

Creating a Class

A class is a blueprint for objects. Use __init__ to set up initial state.

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

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

buddy = Dog("Buddy", "Golden Retriever")
print(buddy.bark())

Class Attributes

Attributes shared across all instances of a class.

class Elevator:
    occupancy_limit = 8

    def __init__(self, occupants):
        if occupants > self.occupancy_limit:
            print(f"Limit exceeded. {occupants - self.occupancy_limit} must exit.")
        self.occupants = occupants

e1 = Elevator(6)
e2 = Elevator(10)
print(e1.occupants, e2.occupants)

Course Example: CameraPhone (Multiple Inheritance)

A class can inherit from more than one parent.

class MobilePhone:
    def __init__(self, memory):
        self.memory = memory

class Camera:
    def take_picture(self):
        print("Say cheese!")

class CameraPhone(MobilePhone, Camera):
    pass

cp = CameraPhone("200KB")
cp.take_picture()
print(cp.memory)

Course Example: Circle Class

A class that calculates geometric properties.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

    def circumference(self):
        return 2 * math.pi * self.radius

    def change_radius(self, new_radius):
        self.radius = new_radius

c = Circle(7)
print(c.area())
c.change_radius(10)
print(c.area())

📝 Exercise: Bank Account

Create a BankAccount class with deposit, withdraw, and get_balance methods.

code.py
Output

            
← Back to Chapter