KAHIBARO Bookshelves
Discord Login Register

13.7. Simple OOP examples

A Simple “Bank Account” Class

Let’s build a small but realistic example: a bank account.

We’ll use:

  • A class
  • Attributes (data)
  • Methods (actions)
  • The __init__ method
  • Simple encapsulation (with a “private” attribute)
  • Multiple objects of the same class
class BankAccount:
    def __init__(self, owner, balance=0):
        # "private" attribute by convention (single underscore)
        self._owner = owner
        self._balance = balance
    def deposit(self, amount):
        if amount <= 0:
            print("Deposit amount must be positive.")
            return
        self._balance += amount
        print(f"Deposited {amount}. New balance: {self._balance}")
    def withdraw(self, amount):
        if amount <= 0:
            print("Withdrawal amount must be positive.")
            return
        if amount > self._balance:
            print("Insufficient funds.")
            return
        self._balance -= amount
        print(f"Withdrew {amount}. New balance: {self._balance}")
    def get_balance(self):
        return self._balance
    def get_owner(self):
        return self._owner
# Using the class
account1 = BankAccount("Alice", 100)
account2 = BankAccount("Bob")  # starts with default balance 0
account1.deposit(50)
account1.withdraw(30)
print("Alice's final balance:", account1.get_balance())
account2.deposit(200)
print("Bob's balance:", account2.get_balance())

Things to notice (without re‑explaining the theory):

  • BankAccount is the blueprint.
  • account1 and account2 are different objects with their own data.
  • Methods like deposit and withdraw use and change the object’s state.
  • The balance is only changed through methods (encapsulation style).

You can extend this yourself with a transfer_to(other_account, amount) method that withdraws from one account and deposits into the other.

A “To-Do Task” Class

Next, a very simple object you might use in a to-do list app.

class Task:
    def __init__(self, title, priority=3):
        self.title = title
        self.priority = priority  # 1 = high, 5 = low
        self.completed = False
    def mark_completed(self):
        self.completed = True
    def mark_pending(self):
        self.completed = False
    def __str__(self):
        status = "✓" if self.completed else "✗"
        return f"[{status}] ({self.priority}) {self.title}"
# Creating and using tasks
task1 = Task("Buy groceries", priority=2)
task2 = Task("Finish Python homework", priority=1)
print(task1)
print(task2)
task1.mark_completed()
print("After completing task1:")
print(task1)

Key ideas shown here:

  • Objects can hold several pieces of related data (title, priority, completed).
  • Methods change the state (mark_completed, mark_pending).
  • __str__ controls how the object is shown when you print it.

A “Rectangle” Class with Methods

Now a small example that uses a bit of math: area and perimeter.

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
    def perimeter(self):
        return 2 * (self.width + self.height)
    def is_square(self):
        return self.width == self.height
# Using the Rectangle class
r1 = Rectangle(4, 5)
r2 = Rectangle(3, 3)
print("r1 area:", r1.area())
print("r1 perimeter:", r1.perimeter())
print("r1 is square?", r1.is_square())
print("r2 area:", r2.area())
print("r2 is square?", r2.is_square())

This example shows:

  • Objects can compute values from their attributes.
  • Methods like area and perimeter don’t change the object; they just return information.
  • The same class can represent different specific rectangles (different widths and heights).

A Simple Inheritance Example: Animals

Let’s combine a base class and child classes that inherit from it.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        # Default / generic behavior
        return "<silent>"
    def info(self):
        return f"I am an animal and my name is {self.name}."
class Dog(Animal):
    def speak(self):
        return "Woof!"
    def fetch(self):
        return f"{self.name} is fetching a ball."
class Cat(Animal):
    def speak(self):
        return "Meow!"
    def scratch(self):
        return f"{self.name} is scratching the sofa..."
# Using the classes
dog = Dog("Buddy")
cat = Cat("Luna")
print(dog.info())        # inherited from Animal
print("Dog says:", dog.speak())  # overridden in Dog
print(dog.fetch())       # only in Dog
print(cat.info())        # inherited from Animal
print("Cat says:", cat.speak())  # overridden in Cat
print(cat.scratch())     # only in Cat

What this demonstrates:

  • Dog and Cat reuse code from Animal.
  • They customize behavior by redefining speak.
  • Each subclass can add extra methods (fetch, scratch) specific to that type.

A Tiny “Shopping Cart” Example

Here we combine multiple objects that work together: products and a shopping cart.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price  # assume a float or int
    def __str__(self):
        return f"{self.name} (${self.price})"
class ShoppingCart:
    def __init__(self):
        self.items = []  # list of Product objects
    def add_item(self, product):
        self.items.append(product)
        print(f"Added {product.name} to the cart.")
    def total_price(self):
        total = 0
        for product in self.items:
            total += product.price
        return total
    def show_items(self):
        if not self.items:
            print("Your cart is empty.")
            return
        print("Items in your cart:")
        for product in self.items:
            print(" -", product)
# Using the classes together
p1 = Product("Book", 12.99)
p2 = Product("Headphones", 39.90)
p3 = Product("Coffee mug", 7.50)
cart = ShoppingCart()
cart.add_item(p1)
cart.add_item(p2)
cart.add_item(p3)
cart.show_items()
print("Total price:", cart.total_price())

This shows:

  • One class (ShoppingCart) containing objects of another class (Product).
  • Methods operating over a collection of objects.
  • A small “system” formed from multiple classes.

Practice Ideas

To solidify these concepts, try these small variations:

  1. BankAccount
    • Add a show_owner method that prints the owner and current balance.
    • Add a simple transfer_to(other_account, amount) method.
  2. Task
    • Add a due_date attribute (as a string to keep it simple).
    • Add a method is_urgent() that returns True for high-priority tasks.
  3. Rectangle
    • Add a method resize(new_width, new_height) that changes the dimensions.
    • Add a method scale(factor) that multiplies width and height by factor.
  4. Animal
    • Add another subclass (e.g. Bird) with its own speak and a new method like fly.
  5. ShoppingCart
    • Add a method remove_item(product_name).
    • Add a simple discount (e.g. 10% off if total is above a certain amount).

In the next chapters and projects, you’ll combine these ideas into larger, more useful programs.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms