Introduction to Python Programming

Andrew J. Pounds, Ph.D.

🏗️ Exercise Eleven: Object-Oriented Programming

So far, you've written programs using variables, functions, and data structures like lists and tuples. This style of programming—where you write step-by-step instructions—is called procedural programming. Now it's time to learn a different approach called Object-Oriented Programming (OOP), which lets you organize your code around "objects" that combine data and behavior together.

What You'll Learn:
  • What Object-Oriented Programming is and why it's useful
  • How to define classes as blueprints for objects
  • How to create objects (instances) from classes
  • How to define attributes (data) and methods (functions) in classes
  • The special __init__ method and the self keyword
  • How to use inheritance to create specialized classes
🏠 Real-World Analogy: The Blueprint and the House

Imagine you're an architect. You create a blueprint that describes what a house should have: rooms, doors, windows, etc. The blueprint itself isn't a house—it's a plan for building houses. From that one blueprint, you can build many actual houses, each with its own address and paint color.

  • Class = The blueprint (the plan)
  • Object = An actual house built from the blueprint
  • Attributes = Properties of the house (color, address, number of rooms)
  • Methods = Things the house can do (open door, turn on lights)

🎯 1. What is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects—entities that contain both data (called attributes) and functions that operate on that data (called methods).

Why Use OOP?

✅ Benefits of Object-Oriented Programming:
  • Organization: Related data and functions are bundled together
  • Reusability: Classes can be reused in different programs
  • Modularity: Changes to one class don't affect others
  • Real-world modeling: Objects naturally represent real-world things
  • Maintenance: Easier to find and fix bugs in well-organized code

Key Terminology

Term Definition Example
Class A blueprint or template for creating objects Dog class
Object An instance of a class—a specific thing created from the blueprint my_dog is a Dog object
Attribute A variable that belongs to an object (its data) my_dog.name
Method A function that belongs to an object (its behavior) my_dog.bark()
Instance Another word for an object created from a class my_dog is an instance of Dog

📐 2. Defining a Class

A class is defined using the class keyword, followed by the class name and a colon. By convention, class names use CamelCase (capitalizing the first letter of each word).

Your First Class

class Dog:
    """A simple class representing a dog"""
    pass  # 'pass' means "do nothing" - placeholder for now

This creates a class called Dog, but it doesn't do anything yet. Let's make it more useful by adding attributes and methods.

Adding Attributes and Methods

class Dog:
    """A class representing a dog"""
    
    def __init__(self, name, breed, age):
        """Initialize dog attributes"""
        self.name = name
        self.breed = breed
        self.age = age
    
    def bark(self):
        """Make the dog bark"""
        print(self.name + " says: Woof! Woof!")
    
    def describe(self):
        """Describe the dog"""
        print(self.name + " is a " + str(self.age) + "-year-old " + self.breed)

Class Diagram: Dog

Dog
Attributes:
- name
- breed
- age
Methods:
+ __init__()
+ bark()
+ describe()
📌 Key Points:
  • class Dog: — Defines a new class named Dog
  • __init__ — Special method that runs when an object is created (the constructor)
  • self — Refers to the current object (more on this below)
  • self.name = name — Creates an attribute and assigns a value to it
  • def bark(self) — Defines a method (function inside a class)

🔨 3. Creating Objects (Instances)

Once you have a class, you can create objects (also called instances) from it. Creating an object is like using the blueprint to build an actual thing.

class Dog:
    """A class representing a dog"""
    
    def __init__(self, name, breed, age):
        self.name = name
        self.breed = breed
        self.age = age
    
    def bark(self):
        print(self.name + " says: Woof! Woof!")
    
    def describe(self):
        print(self.name + " is a " + str(self.age) + "-year-old " + self.breed)

# Create objects (instances) of the Dog class
dog1 = Dog("Buddy", "Golden Retriever", 3)
dog2 = Dog("Max", "German Shepherd", 5)
dog3 = Dog("Bella", "Labrador", 2)

# Access attributes
print(dog1.name)
print(dog2.breed)
print(dog3.age)

# Call methods
dog1.bark()
dog2.describe()
Buddy
German Shepherd
2
Buddy says: Woof! Woof!
Max is a 5-year-old German Shepherd

One Class → Multiple Objects

Dog (Class)
Blueprint for dogs
↓ ↓ ↓
dog1
name = "Buddy"
breed = "Golden Retriever"
age = 3
dog2
name = "Max"
breed = "German Shepherd"
age = 5
dog3
name = "Bella"
breed = "Labrador"
age = 2
💡 Note: Each object has its own copy of the attributes. Changing dog1.name doesn't affect dog2.name.

⚙️ 4. The __init__ Method and self

Understanding __init__

The __init__ method is a special method called the constructor. It runs automatically when you create a new object. Its job is to initialize the object's attributes.

class Student:
    def __init__(self, name, student_id):
        print("Creating a new student...")
        self.name = name
        self.student_id = student_id
        self.grades = []  # Empty list to store grades
        print("Student " + name + " created!")

# When we create a Student, __init__ runs automatically
alice = Student("Alice", "S001")
Creating a new student...
Student Alice created!

Understanding self

The self parameter is a reference to the current object—the specific instance that's being created or whose method is being called.

⚠️ Critical Rule: The first parameter of every method in a class must be self. When you call a method, Python automatically passes the object as the first argument—you don't include it yourself.
class Circle:
    def __init__(self, radius):
        self.radius = radius  # self.radius belongs to THIS circle
    
    def get_area(self):
        return 3.14159 * self.radius ** 2
    
    def get_circumference(self):
        return 2 * 3.14159 * self.radius

# Create two circles with different radii
circle1 = Circle(5)
circle2 = Circle(10)

# Each circle uses its own radius
print("Circle 1 area:", circle1.get_area())
print("Circle 2 area:", circle2.get_area())
Circle 1 area: 78.53975
Circle 2 area: 314.159

How self Works

When You Write Python Interprets It As
circle1.get_area() Circle.get_area(circle1)
dog1.bark() Dog.bark(dog1)
student.add_grade(95) Student.add_grade(student, 95)

🔧 5. Working with Methods

Methods are functions defined inside a class. They can access and modify the object's attributes using self.

Methods That Modify Attributes

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        """Add money to the account"""
        if amount > 0:
            self.balance += amount
            print("Deposited $" + str(amount))
        else:
            print("Deposit amount must be positive")
    
    def withdraw(self, amount):
        """Remove money from the account"""
        if amount > self.balance:
            print("Insufficient funds!")
        elif amount <= 0:
            print("Withdrawal amount must be positive")
        else:
            self.balance -= amount
            print("Withdrew $" + str(amount))
    
    def get_balance(self):
        """Return current balance"""
        return self.balance
    
    def display_info(self):
        """Display account information"""
        print("Account owner: " + self.owner)
        print("Balance: $" + str(self.balance))

# Create an account and use its methods
account = BankAccount("Alice", 100)

account.display_info()
print()

account.deposit(50)
account.withdraw(30)
account.withdraw(200)  # Try to withdraw too much
print()

print("Final balance: $" + str(account.get_balance()))
Account owner: Alice
Balance: $100

Deposited $50
Withdrew $30
Insufficient funds!

Final balance: $120

Methods That Return Values

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def get_area(self):
        return self.width * self.height
    
    def get_perimeter(self):
        return 2 * (self.width + self.height)
    
    def is_square(self):
        return self.width == self.height

# Create rectangles and use methods
rect1 = Rectangle(4, 6)
rect2 = Rectangle(5, 5)

print("Rectangle 1: " + str(rect1.width) + " x " + str(rect1.height))
print("Area:", rect1.get_area())
print("Perimeter:", rect1.get_perimeter())
print("Is square?", rect1.is_square())
print()
print("Rectangle 2: " + str(rect2.width) + " x " + str(rect2.height))
print("Is square?", rect2.is_square())
Rectangle 1: 4 x 6
Area: 24
Perimeter: 20
Is square? False

Rectangle 2: 5 x 5
Is square? True

👨‍👧‍👦 6. Inheritance: Building on Existing Classes

Inheritance allows you to create a new class based on an existing class. The new class (called the child or subclass) inherits all the attributes and methods of the original class (called the parent or superclass), and can add or modify them.

🚗 Analogy: Think of a general "Vehicle" class. Cars, motorcycles, and trucks are all vehicles—they share common features (wheels, engine, can move), but each has specific differences. Instead of rewriting common code, we can create a Vehicle class and have Car, Motorcycle, and Truck inherit from it.

Basic Inheritance

# Parent class (superclass)
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def eat(self):
        print(self.name + " is eating.")
    
    def sleep(self):
        print(self.name + " is sleeping.")

# Child class (subclass) - inherits from Animal
class Dog(Animal):  # Put parent class in parentheses
    def __init__(self, name, age, breed):
        super().__init__(name, age)  # Call parent's __init__
        self.breed = breed  # Add new attribute
    
    def bark(self):  # Add new method
        print(self.name + " says: Woof!")

# Child class - Cat
class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color
    
    def meow(self):
        print(self.name + " says: Meow!")

# Create objects
dog = Dog("Buddy", 3, "Golden Retriever")
cat = Cat("Whiskers", 5, "Orange")

# Dogs and cats can use inherited methods
dog.eat()   # Inherited from Animal
dog.sleep() # Inherited from Animal
dog.bark()  # Defined in Dog

print()

cat.eat()   # Inherited from Animal
cat.meow()  # Defined in Cat
Buddy is eating.
Buddy is sleeping.
Buddy says: Woof!

Whiskers is eating.
Whiskers says: Meow!

Inheritance Hierarchy

Animal (Parent)
- name
- age
+ eat()
+ sleep()
↙ ↘
Dog (Child)
- name (inherited)
- age (inherited)
- breed (new)
+ eat() (inherited)
+ sleep() (inherited)
+ bark() (new)
Cat (Child)
- name (inherited)
- age (inherited)
- color (new)
+ eat() (inherited)
+ sleep() (inherited)
+ meow() (new)

Understanding super()

The super() function lets you call methods from the parent class. This is especially useful in __init__ to initialize inherited attributes:

class Vehicle:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year
    
    def start(self):
        print("Vehicle starting...")

class Car(Vehicle):
    def __init__(self, brand, model, year, num_doors):
        # Call parent's __init__ to set brand, model, year
        super().__init__(brand, model, year)
        # Then set car-specific attribute
        self.num_doors = num_doors
    
    def start(self):  # Override parent method
        print("Car engine starting... Vroom!")
    
    def honk(self):
        print("Beep beep!")

my_car = Car("Toyota", "Camry", 2022, 4)
print(my_car.brand, my_car.model, my_car.year)
print("Doors:", my_car.num_doors)
my_car.start()  # Uses Car's version, not Vehicle's
Toyota Camry 2022
Doors: 4
Car engine starting... Vroom!

✨ 7. Special Methods (Magic Methods)

Python has special methods (also called magic methods or dunder methods) that have double underscores before and after their names. These methods let you define how your objects behave with built-in operations.

Common Special Methods

Method Purpose Called When
__init__(self) Initialize object Object is created
__str__(self) String representation print(obj) or str(obj)
__repr__(self) Official string representation Typing object name in console
__len__(self) Return length len(obj)
__eq__(self, other) Equality comparison obj1 == obj2

The __str__ Method

Without __str__, printing an object gives an unhelpful message:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(p)
<__main__.Point object at 0x7f9b8c0d5f10>

With __str__, you control what gets printed:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return "Point(" + str(self.x) + ", " + str(self.y) + ")"

p = Point(3, 4)
print(p)
Point(3, 4)

Complete Example with Special Methods

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
    
    def __str__(self):
        return self.title + " by " + self.author
    
    def __len__(self):
        return self.pages
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author

# Create books
book1 = Book("Python Basics", "John Smith", 250)
book2 = Book("Python Basics", "John Smith", 250)
book3 = Book("Data Science", "Jane Doe", 400)

# Use special methods
print(book1)          # Uses __str__
print("Pages:", len(book1))  # Uses __len__
print("book1 == book2:", book1 == book2)  # Uses __eq__
print("book1 == book3:", book1 == book3)
Python Basics by John Smith
Pages: 250
book1 == book2: True
book1 == book3: False

🎯 8. Complete Examples

Example 1: Student Grade Tracker

class Student:
    def __init__(self, name, student_id):
        self.name = name
        self.student_id = student_id
        self.grades = []
    
    def add_grade(self, grade):
        if 0 <= grade <= 100:
            self.grades.append(grade)
        else:
            print("Invalid grade. Must be between 0 and 100.")
    
    def get_average(self):
        if len(self.grades) == 0:
            return 0
        return sum(self.grades) / len(self.grades)
    
    def get_letter_grade(self):
        avg = self.get_average()
        if avg >= 90:
            return "A"
        elif avg >= 80:
            return "B"
        elif avg >= 70:
            return "C"
        elif avg >= 60:
            return "D"
        else:
            return "F"
    
    def __str__(self):
        return self.name + " (" + self.student_id + ")"

# Create students and add grades
print("=== Student Grade Tracker ===")
print()

alice = Student("Alice Johnson", "S001")
alice.add_grade(92)
alice.add_grade(88)
alice.add_grade(95)
alice.add_grade(91)

bob = Student("Bob Smith", "S002")
bob.add_grade(78)
bob.add_grade(82)
bob.add_grade(75)
bob.add_grade(80)

# Display results
for student in [alice, bob]:
    print(student)
    print(" Grades:", student.grades)
    print(" Average:", round(student.get_average(), 2))
    print(" Letter Grade:", student.get_letter_grade())
    print()
=== Student Grade Tracker ===

Alice Johnson (S001)
  Grades: [92, 88, 95, 91]
  Average: 91.5
  Letter Grade: A

Bob Smith (S002)
  Grades: [78, 82, 75, 80]
  Average: 78.75
  Letter Grade: C

Example 2: Shopping Cart

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price
    
    def __str__(self):
        return self.name + " ($" + str(self.price) + ")"

class ShoppingCart:
    def __init__(self):
        self.items = []  # List of (product, quantity) tuples
    
    def add_item(self, product, quantity=1):
        self.items.append((product, quantity))
        print("Added " + str(quantity) + "x " + product.name + " to cart")
    
    def get_total(self):
        total = 0
        for product, quantity in self.items:
            total += product.price * quantity
        return total
    
    def display(self):
        print("\\n=== Shopping Cart ===")
        for product, quantity in self.items:
            subtotal = product.price * quantity
            print(str(quantity) + "x " + product.name + " @ $" + str(product.price) + " = $" + str(subtotal))
        print("-" * 30)
        print("Total: $" + str(self.get_total()))
    
    def __len__(self):
        return len(self.items)

# Create products
apple = Product("Apple", 0.99)
bread = Product("Bread", 2.49)
milk = Product("Milk", 3.99)

# Create cart and add items
cart = ShoppingCart()
cart.add_item(apple, 5)
cart.add_item(bread, 2)
cart.add_item(milk, 1)

# Display cart
cart.display()
print("\\nNumber of different items:", len(cart))
Added 5x Apple to cart
Added 2x Bread to cart
Added 1x Milk to cart

=== Shopping Cart ===
5x Apple @ $0.99 = $4.95
2x Bread @ $2.49 = $4.98
1x Milk @ $3.99 = $3.99
------------------------------
Total: $13.92

Number of different items: 3

Example 3: Inheritance with Shapes

import math

class Shape:
    """Base class for all shapes"""
    def __init__(self, name):
        self.name = name
    
    def get_area(self):
        pass  # To be implemented by child classes
    
    def get_perimeter(self):
        pass  # To be implemented by child classes
    
    def describe(self):
        print(self.name + ":")
        print(" Area:", round(self.get_area(), 2))
        print(" Perimeter:", round(self.get_perimeter(), 2))

class Rectangle(Shape):
    def __init__(self, width, height):
        super().__init__("Rectangle")
        self.width = width
        self.height = height
    
    def get_area(self):
        return self.width * self.height
    
    def get_perimeter(self):
        return 2 * (self.width + self.height)

class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius
    
    def get_area(self):
        return math.pi * self.radius ** 2
    
    def get_perimeter(self):
        return 2 * math.pi * self.radius

class Triangle(Shape):
    def __init__(self, a, b, c):
        super().__init__("Triangle")
        self.a = a
        self.b = b
        self.c = c
    
    def get_area(self):
        # Heron's formula
        s = self.get_perimeter() / 2
        return math.sqrt(s * (s-self.a) * (s-self.b) * (s-self.c))
    
    def get_perimeter(self):
        return self.a + self.b + self.c

# Create different shapes
print("=== Shape Calculator ===")
print()

shapes = [
    Rectangle(5, 3),
    Circle(4),
    Triangle(3, 4, 5)
]

for shape in shapes:
    shape.describe()
    print()
=== Shape Calculator ===

Rectangle:
  Area: 15
  Perimeter: 16

Circle:
  Area: 50.27
  Perimeter: 25.13

Triangle:
  Area: 6.0
  Perimeter: 12

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Forgetting self in Method Definition

❌ Wrong:
class Dog:
    def __init__(name):  # Missing self!
        self.name = name
✅ Correct:
class Dog:
    def __init__(self, name):  # self is first parameter
        self.name = name

Mistake 2: Forgetting self. When Accessing Attributes

❌ Wrong:
class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        print(name + " says Woof!")  # ERROR! 'name' not defined
✅ Correct:
class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        print(self.name + " says Woof!")  # Use self.name

Mistake 3: Passing self When Calling a Method

❌ Wrong:
dog = Dog("Buddy")
dog.bark(dog)  # ERROR! Don't pass self manually
✅ Correct:
dog = Dog("Buddy")
dog.bark()  # Python passes 'dog' as self automatically

Mistake 4: Forgetting to Call super().__init__()

❌ Wrong:
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        self.breed = breed  # self.name is never set!
✅ Correct:
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call parent's __init__
        self.breed = breed

Mistake 5: Using Class Name Instead of self

❌ Wrong:
class Counter:
    def __init__(self):
        Counter.count = 0  # This creates a class variable!
    
    def increment(self):
        Counter.count += 1
✅ Correct:
class Counter:
    def __init__(self):
        self.count = 0  # Instance variable
    
    def increment(self):
        self.count += 1

✏️ Practice Exercises

Try writing these programs on your own!

Exercise 1: Temperature Class

Create a Temperature class that:

  1. Stores a temperature in Celsius
  2. Has a method to_fahrenheit() that returns the temperature in Fahrenheit
  3. Has a method to_kelvin() that returns the temperature in Kelvin
  4. Has a __str__ method that displays the temperature nicely

Formulas: F = C × 9/5 + 32, K = C + 273.15

Exercise 2: Library Book

Create a LibraryBook class with:

  • Attributes: title, author, is_checked_out (boolean)
  • Methods: check_out(), return_book(), __str__()

The check_out method should only work if the book isn't already checked out.

Exercise 3: Playlist

Create a Song class and a Playlist class:

  • Song: title, artist, duration (in seconds)
  • Playlist: name, list of songs

Add methods to the Playlist to add songs, get total duration, and display all songs.

Exercise 4: Employee Hierarchy

Create an inheritance hierarchy:

  • Employee (base class): name, employee_id, salary
  • Manager (inherits from Employee): adds department and list of team members
  • Developer (inherits from Employee): adds programming_language

Include appropriate methods for each class.

Exercise 5: Game Character

Create a Character class for a simple game:

  • Attributes: name, health (default 100), attack_power, defense
  • Methods: attack(other_character), take_damage(amount), is_alive(), heal(amount)

Create two characters and simulate a battle!

Exercise 6: Quiz System

Create classes for a quiz system:

  • Question: question_text, correct_answer, points
  • Quiz: title, list of questions

The Quiz should have methods to add questions, take the quiz (ask each question and check answers), and display the final score.

📋 Quick Reference

Class Definition

class ClassName:
    def __init__(self, param1, param2):
        self.attribute1 = param1
        self.attribute2 = param2
    
    def method_name(self):
        # method code
        pass

Creating and Using Objects

Create object:
obj = ClassName(arg1, arg2)
Access attribute:
obj.attribute_name
Call method:
obj.method_name()
Modify attribute:
obj.attribute = new_value

Inheritance

class ChildClass(ParentClass):
    def __init__(self, parent_params, child_params):
        super().__init__(parent_params)
        self.child_attribute = child_params

⭐ Key Takeaways

  • ✓ A class is a blueprint; an object is an instance of that blueprint
  • ✓ Classes combine attributes (data) and methods (functions)
  • ✓ __init__ is the constructor—it initializes new objects
  • ✓ self refers to the current object—always the first parameter in methods
  • ✓ Use self.attribute to access or modify an object's data
  • ✓ Inheritance lets you create new classes based on existing ones
  • ✓ Use super() to call parent class methods
  • ✓ Special methods like __str__ customize how objects behave
  • ✓ Use classes when you have entities with both data and behavior
  • ✓ OOP helps organize code, making it reusable and maintainable

❓ Need Help?

If your program doesn't work, check these common issues:

  1. TypeError: method() takes 0 positional arguments but 1 was given—Did you forget self in the method definition?
  2. AttributeError: object has no attribute 'x'—Did you use self. when setting the attribute in __init__?
  3. NameError: name 'attribute' is not defined—Did you forget self. when accessing the attribute?
  4. Parent attributes missing—Did you call super().__init__() in the child class?
💡 Debugging Tip: Print self and its attributes to see what's happening:
def some_method(self):
    print("self:", self)
    print("self.name:", self.name)
    # ... rest of method
Remember: Object-Oriented Programming is a powerful way to organize code by modeling real-world things. It takes practice to think in terms of objects, but once you do, you'll find it makes complex programs much easier to write and understand. Start simple—create classes for things you can visualize (animals, vehicles, books)—and gradually work up to more abstract concepts!