python magic dunder methods __str__ __repr__ __len__ 2024 Challenge
Read the problem description and solve the challenge in the workspace.
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
BankAccountobject. - 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-newBankAccountobject 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 anownerandbalanceattributes usingself. - The User vs. Developer View: Remember that
__str__is what gets called when the user tries toprint()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 theownerandbalanceabout bothselfandother. - Don't Break Logic Expectations: Your overloaded
+operator should intuitively add things together; make sure it creates and returns a newBankAccountobject 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).