Bird
Raised Fist0

How would you modify this procedural code to use an object-oriented approach for managing a bank account?

hard🚀 Application Q9 of Q15
Python - Object-Oriented Programming Foundations
How would you modify this procedural code to use an object-oriented approach for managing a bank account?
balance = 1000
def deposit(amount):
    global balance
    balance += amount
def withdraw(amount):
    global balance
    balance -= amount

deposit(500)
withdraw(200)
print(balance)
AKeep functions as is but add a class wrapper
BUse global variables inside a class without methods
CDefine deposit and withdraw as static methods without balance
DCreate a BankAccount class with balance attribute and deposit, withdraw methods
Step-by-Step Solution
Solution:
  1. Step 1: Understand procedural code with global balance

    The code uses a global variable and functions to modify it, which is procedural style.
  2. Step 2: Convert to OOP by encapsulating balance and methods

    Creating a class with balance as an attribute and deposit/withdraw as methods encapsulates data and behavior properly.
  3. Final Answer:

    Create a BankAccount class with balance attribute and deposit, withdraw methods -> Option D
  4. Quick Check:

    OOP encapsulates state and behavior in objects [OK]
Quick Trick: Encapsulate data and functions inside a class [OK]
Common Mistakes:
MISTAKES
  • Using global variables inside classes
  • Making methods static without state
  • Not encapsulating balance properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes