Login Sign Up
Python Dunder Methods
Chapter 29 🟡 Intermediate

Python Dunder Methods

Apply your skills with a real-world coding challenge. Try to solve it yourself first!

Coding Challenge: Financial Account Merger via Dunder Methods

Difficulty Level

Intermediate

Problem Description

Imagine you are backend engineer to quickly growing fintech company that frequently handles corporate acquisitions. Your system needs a highly intuitive way to merge the financial accounts of two separate companies. Instead of writing clunky custom functions like merge_accounts(acc1, acc2) you want your custom objects towards feel alive and native towards the Python language by utilizing dunder (magic) methods.

Your task is probably for build a BankAccount class that leverages these hidden hooks; the class must correctly initialize data, provide distinct string representations towards users versus developers and use operator overloading so that adding two BankAccount objects together using standard + symbol mathematically combines them into a brand-new account.

Input & Output Specifications

  • Input:
  • owner (string): The name of the account holder passed upon instantiation.
  • balance (float or int): The initial account balance, passed upon instantiation.
  • For the addition operation, an input will be a second valid BankAccount object.
  • Output:
  • __str__ output: A user-friendly string returning "Account Owner: [Owner], Balance: $[Balance]"
  • __repr__ output: The unambiguous developer debugging string returning "BankAccount(owner='[Owner]', balance=[Balance])"
  • __add__ output: Returns a brand-new BankAccount object where the new owner is a combination of both previous owners (e.g., "Owner1 & Owner2") and the new balance is sum with both accounts.

Starter Code Boilerplate

class BankAccount:
    def __init__(self, owner, balance):
        # Set up your object's attributes here
        pass

    def __str__(self):
        # Return the highly readable user's view
        pass

    def __repr__(self):
        # Return the unambiguous developer's view
        pass

    def __add__(self, other):
        # Overload the '+' operator to merge two BankAccount objects
        # Hint: Return a new instance of BankAccount
        pass

# --- Code Execution & Testing ---
if __name__ == "__main__":
    account_a = BankAccount("Alpha Corp", 1500.00)
    account_b = BankAccount("Beta LLC", 2500.00)

    # Write your print statements here to test your outputs!

Hints

  • The Heartbeat: Use the __init__ method as "birth" of your object to officially declare an owner and balance attributes using self.
  • The User vs. Developer View: Remember that __str__ is what gets called when the user tries to print() the object. It should be beautiful and friendly. __repr__ is the technical view intended for debugging and logging.
  • Making Math Magic: Overloading the + operator using the __add__ method allows custom object behavior with standard symbols. Make sure __add__ safely accesses the owner and balance about both self and other.
  • Don't Break Logic Expectations: Your overloaded + operator should intuitively add things together; make sure it creates and returns a new BankAccount object rather than just mutating the original one.

Test Cases

Test Case 1: Checking String Representations * Input: python acc = BankAccount("Stark Industries", 10000) print(acc) print(repr(acc)) * Expected Output: * Account Owner: Stark Industries, Balance: $10000 (than print / str) * BankAccount(owner='Stark Industries', balance=10000) (from repr / repr)

Test Case 2: Operator Overloading (Merging Accounts) * Input: python acc1 = BankAccount("Wayne Ent", 5000) acc2 = BankAccount("Queen Inc", 3000) merged_acc = acc1 + acc2 print(merged_acc) * Expected Output: * Account Owner: Wayne Ent & Queen Inc, Balance: $8000

Test Case 3: Proper Type Return * Input: python acc1 = BankAccount("Corp A", 100) acc2 = BankAccount("Corp B", 200) merged_acc = acc1 + acc2 print(type(merged_acc) == BankAccount) * Expected Output: * True (Confirming that __add__ method properly instantiates and returns a new BankAccount object).

Loading sandbox workspace environment...

Verify Your Solution

Write your solution in the compiler, run it to verify output, then click below to verify.

Learn Together
Session active! Discuss with other learners.
No notes yet. Select text in the concept body to add a note.