-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclasses.py
More file actions
351 lines (284 loc) · 10.3 KB
/
classes.py
File metadata and controls
351 lines (284 loc) · 10.3 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
Classes and Objects Exercises - Complete the classes below
Run this file with: python topic.py
Or work interactively with: python3 -i topic.py
"""
from datetime import datetime
# Exercise 1: Basic Class Definition
class Person:
"""A class representing a person with name and age."""
def __init__(self, name, age):
"""Initialize a person with name and age."""
# Your code here
pass
def __str__(self):
"""Return string representation of the person."""
# Your code here
pass
# Exercise 2: Simple Methods (add to Person class above)
def get_name(self):
"""Return the person's name."""
# Your code here
pass
def get_age(self):
"""Return the person's age."""
# Your code here
pass
def have_birthday(self):
"""Increase age by 1."""
# Your code here
pass
def is_adult(self):
"""Return True if age >= 18."""
# Your code here
pass
# Exercise 3: Class with Behavior
class BankAccount:
"""A class representing a bank account."""
def __init__(self, account_holder, initial_balance=0):
"""Initialize account with holder name and optional initial balance."""
# Your code here
pass
def deposit(self, amount):
"""Add amount to the balance."""
# Your code here
pass
def withdraw(self, amount):
"""Subtract amount from balance if sufficient funds."""
# Your code here
pass
def get_balance(self):
"""Return current balance."""
# Your code here
pass
def __str__(self):
"""Return string representation of the account."""
# Your code here
pass
# Exercise 4: Class with Validation
class Rectangle:
"""A class representing a rectangle with width and height."""
def __init__(self, width, height):
"""Initialize rectangle with width and height (must be positive)."""
# Your code here - include validation
pass
def get_area(self):
"""Calculate and return the area (width * height)."""
# Your code here
pass
def get_perimeter(self):
"""Calculate and return the perimeter."""
# Your code here
pass
def is_square(self):
"""Return True if width equals height."""
# Your code here
pass
# Exercise 5: Class with Lists
class ShoppingCart:
"""A class representing a shopping cart."""
def __init__(self):
"""Initialize an empty shopping cart."""
# Your code here
pass
def add_item(self, item, price):
"""Add an item with its price to the cart."""
# Your code here
pass
def remove_item(self, item):
"""Remove an item from the cart."""
# Your code here
pass
def get_total(self):
"""Calculate and return the total price of all items."""
# Your code here
pass
def get_items(self):
"""Return a list of all items in the cart."""
# Your code here
pass
def is_empty(self):
"""Return True if the cart is empty."""
# Your code here
pass
# Exercise 6: Class Relationships
class Student:
"""A class representing a student with grades."""
def __init__(self, name, student_id):
"""Initialize student with name and ID."""
# Your code here
pass
def add_grade(self, subject, grade):
"""Add a grade for a subject."""
# Your code here
pass
def get_grade(self, subject):
"""Get the grade for a specific subject."""
# Your code here
pass
def get_gpa(self):
"""Calculate and return the GPA (average of all grades)."""
# Your code here
pass
def get_subjects(self):
"""Return a list of all subjects."""
# Your code here
pass
# Exercise 7: Class with Class Attributes
class Car:
"""A class representing a car with class-level counting."""
total_cars = 0 # Class attribute to count all cars
def __init__(self, make, model, year):
"""Initialize car with make, model, and year."""
# Your code here - don't forget to increment total_cars
pass
def get_age(self):
"""Calculate and return the age of the car."""
current_year = datetime.now().year
# Your code here
pass
def __str__(self):
"""Return string representation of the car."""
# Your code here
pass
@classmethod
def get_total_cars(cls):
"""Return the total number of cars created."""
# Your code here
pass
# Exercise 8: Multiple Object Interaction
class Library:
"""A class representing a library with books."""
def __init__(self):
"""Initialize empty library."""
# Your code here
pass
def add_book(self, title, author):
"""Add a book to the library."""
# Your code here
pass
def find_books_by_author(self, author):
"""Find all books by a specific author."""
# Your code here
pass
def checkout_book(self, title):
"""Mark a book as checked out."""
# Your code here
pass
def return_book(self, title):
"""Mark a book as available."""
# Your code here
pass
def get_available_books(self):
"""Return list of available books."""
# Your code here
pass
# Exercise 9: Advanced Class Features
class Temperature:
"""A class representing temperature with multiple scales."""
def __init__(self, celsius):
"""Initialize with temperature in Celsius."""
# Your code here
pass
@property
def celsius(self):
"""Get temperature in Celsius."""
# Your code here
pass
@celsius.setter
def celsius(self, value):
"""Set temperature in Celsius."""
# Your code here
pass
@property
def fahrenheit(self):
"""Get temperature in Fahrenheit."""
# Your code here - convert from Celsius
pass
@fahrenheit.setter
def fahrenheit(self, value):
"""Set temperature in Fahrenheit."""
# Your code here - convert to Celsius
pass
@property
def kelvin(self):
"""Get temperature in Kelvin."""
# Your code here - convert from Celsius
pass
@kelvin.setter
def kelvin(self, value):
"""Set temperature in Kelvin."""
# Your code here - convert to Celsius
pass
def __str__(self):
"""Return string showing temperature in all scales."""
# Your code here
pass
def run_tests():
"""Test all the classes to verify they work correctly."""
print("Testing Person class:")
person = Person("Alice", 25)
print(f"Person: {person}") # Should show Person(name=Alice, age=25)
print(f"Name: {person.get_name()}") # Should print Alice
print(f"Is adult: {person.is_adult()}") # Should print True
person.have_birthday()
print(f"After birthday: {person.get_age()}") # Should print 26
print("\nTesting BankAccount class:")
account = BankAccount("Bob", 100)
print(f"Account: {account}") # Should show account info
account.deposit(50)
print(f"After deposit: {account.get_balance()}") # Should print 150
account.withdraw(30)
print(f"After withdrawal: {account.get_balance()}") # Should print 120
print("\nTesting Rectangle class:")
rect = Rectangle(4, 5)
print(f"Area: {rect.get_area()}") # Should print 20
print(f"Perimeter: {rect.get_perimeter()}") # Should print 18
print(f"Is square: {rect.is_square()}") # Should print False
square = Rectangle(4, 4)
print(f"Square is square: {square.is_square()}") # Should print True
print("\nTesting ShoppingCart class:")
cart = ShoppingCart()
print(f"Empty cart: {cart.is_empty()}") # Should print True
cart.add_item("Apple", 1.50)
cart.add_item("Banana", 0.75)
print(f"Total: {cart.get_total()}") # Should print 2.25
print(f"Items: {cart.get_items()}") # Should print ['Apple', 'Banana']
print("\nTesting Student class:")
student = Student("Charlie", "S123")
student.add_grade("Math", 85)
student.add_grade("Science", 92)
print(f"Math grade: {student.get_grade('Math')}") # Should print 85
print(f"GPA: {student.get_gpa()}") # Should print 88.5
print(f"Subjects: {student.get_subjects()}") # Should print ['Math', 'Science']
print("\nTesting Car class:")
print(f"Total cars before: {Car.get_total_cars()}") # Should print 0
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2018)
print(f"Car1: {car1}")
print(f"Car1 age: {car1.get_age()}") # Should print current year - 2020
print(f"Total cars after: {Car.get_total_cars()}") # Should print 2
print("\nTesting Library class:")
library = Library()
library.add_book("1984", "George Orwell")
library.add_book("Animal Farm", "George Orwell")
library.add_book("To Kill a Mockingbird", "Harper Lee")
orwell_books = library.find_books_by_author("George Orwell")
print(f"Orwell books: {orwell_books}") # Should print 2 books
library.checkout_book("1984")
available = library.get_available_books()
print(f"Available books: {len(available)}") # Should print 2
print("\nTesting Temperature class:")
temp = Temperature(0) # 0 Celsius
print(f"Temperature: {temp}") # Should show all three scales
print(f"Fahrenheit: {temp.fahrenheit}") # Should print 32.0
print(f"Kelvin: {temp.kelvin}") # Should print 273.15
temp.fahrenheit = 100
print(f"After setting to 100F: {temp.celsius}") # Should print ~37.78
if __name__ == "__main__":
print("Python Classes and Objects Exercises")
print("=" * 50)
print("Complete the classes above, then run this file to test them.")
print("Uncomment the line below when you're ready to test:")
print()
# run_tests() # Uncomment this line to run tests