-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoop_exercises.py
More file actions
128 lines (103 loc) · 4.5 KB
/
Copy pathoop_exercises.py
File metadata and controls
128 lines (103 loc) · 4.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# ==========================================
# Python Learning Lab: 05 OOP
# ==========================================
print("--- Running OOP Exercises ---")
# ==========================================
# Challenge 1: Basic Class & Encapsulation
# ==========================================
# Implement a `BankAccount` class with:
# - A private attribute `__balance` initialized to a given amount.
# - A property getter `balance` to view the balance.
# - A method `deposit(amount)` that increases balance.
# - A method `withdraw(amount)` that decreases balance if sufficient funds exist,
# otherwise raises a ValueError.
class BankAccount:
def __init__(self, initial_balance):
# TODO: Initialize private balance variable
self.__balance = initial_balance
@property
def balance(self):
# TODO: Return private balance
return self.__balance
def deposit(self, amount):
# TODO: Increase private balance
self.__balance += amount
def withdraw(self, amount):
# TODO: Decrease balance or raise ValueError
if amount > self.__balance:
raise ValueError("Insufficient funds")
self.__balance -= amount
# --- Verification ---
account = BankAccount(100)
assert account.balance == 100, "Getter failed to retrieve correct balance"
account.deposit(50)
assert account.balance == 150, "Deposit failed to update balance"
account.withdraw(30)
assert account.balance == 120, "Withdrawal failed to update balance"
try:
account.withdraw(500)
assert False, "Should raise ValueError for overdraft"
except ValueError:
print("✓ Challenge 1 passed!")
# ==========================================
# Challenge 2: Inheritance & Polymorphism
# ==========================================
# Implement a parent class `Employee` and child class `Developer`:
# - `Employee` has: name (str), base_salary (float). Method `calculate_pay()` returns base_salary.
# - `Developer` inherits from `Employee` and adds: programming_language (str).
# - `Developer` overrides `calculate_pay()` to return base_salary + a bonus of 1000.0.
class Employee:
def __init__(self, name, base_salary):
# TODO: Set attributes
self.name = name
self.base_salary = base_salary
def calculate_pay(self):
# TODO: Return base salary
return self.base_salary
class Developer(Employee):
def __init__(self, name, base_salary, programming_language):
# TODO: Call parent constructor and set language
super().__init__(name, base_salary)
self.programming_language = programming_language
def calculate_pay(self):
# TODO: Return base salary + 1000.0 bonus
return self.base_salary + 1000.0
# --- Verification ---
emp = Employee("Alice", 5000.0)
dev = Developer("Bob", 6000.0, "Python")
assert emp.calculate_pay() == 5000.0, "Employee pay calculation incorrect"
assert dev.calculate_pay() == 7000.0, "Developer pay calculation incorrect"
assert dev.programming_language == "Python", "Developer language attribute missing"
print("✓ Challenge 2 passed!")
# ==========================================
# Challenge 3: Dunder Methods
# ==========================================
# Create a `Book` class representing a book in a library:
# - Attributes: title (str), author (str), pages (int).
# - Dunder `__str__`: Returns string format "[title] by [author]".
# - Dunder `__len__`: Returns page count.
# - Dunder `__eq__`: Compares two books; returns True if title and author are identical.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# TODO: Implement dunder methods
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return self.pages
def __eq__(self, other):
if not isinstance(other, Book):
return False
return self.title == other.title and self.author == other.author
# --- Verification ---
book1 = Book("Python Basics", "Guido van Rossum", 250)
book2 = Book("Python Basics", "Guido van Rossum", 250)
book3 = Book("Advanced Python", "Raymond Hettinger", 450)
assert str(book1) == "Python Basics by Guido van Rossum", f"Expected 'Python Basics by Guido van Rossum', got '{str(book1)}'"
assert len(book1) == 250, f"Expected page length 250, got {len(book1)}"
assert book1 == book2, "Books with same title and author should be equal"
assert book1 != book3, "Different books should not be equal"
print("✓ Challenge 3 passed!")
print("\n🎉 All tests passed successfully!")