Skip to main content Brad's PyNotes

Classes: Object-Oriented Programming in Python

TL;DR

Python classes bundle data and functionality together, supporting inheritance, method overriding, and special methods for creating powerful, reusable object-oriented code.

Interesting!

Python’s “everything is an object” philosophy means even classes are objects - you can inspect class attributes, pass classes as arguments, and create classes dynamically at runtime.

Basic Class Definition

python code snippet start

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name} and I'm {self.age} years old"
    
    def have_birthday(self):
        self.age += 1

# Usage
alice = Person("Alice", 30)
print(alice.greet())  # Hello, I'm Alice and I'm 30 years old
alice.have_birthday()
print(alice.age)  # 31

python code snippet end

Inheritance

python code snippet start

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id
        self.grades = []
    
    def add_grade(self, grade):
        self.grades.append(grade)
    
    def greet(self):  # Method overriding
        return f"Hi, I'm {self.name}, student #{self.student_id}"

bob = Student("Bob", 20, "S12345")
print(bob.greet())  # Hi, I'm Bob, student #S12345

python code snippet end

Special Methods

python code snippet start

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
    
    def __str__(self):
        return f"Account balance: ${self.balance}"
    
    def __add__(self, amount):
        return BankAccount(self.balance + amount)

account = BankAccount(100)
print(account)  # Account balance: $100
new_account = account + 50
print(new_account)  # Account balance: $150

python code snippet end

Classes enable code organization, reusability, and modeling real-world concepts in your programs.

Modern Python classes work beautifully with type hints for better code documentation and IDE support. Advanced features include matrix operators for mathematical classes and integrate with struct module for binary data representation.

Reference: Python Tutorial - Classes