Object-Oriented Programming Assessment
Test your understanding of Python classes, inheritance, magic methods, properties, dataclasses, composition, and polymorphism across 12 exercises.
Create a BankAccount class with:
__init__(self, owner: str, balance: float = 0) storing both as instance attributesdeposit(self, amount) that adds to balance and returns the new balancewithdraw(self, amount) that subtracts from balance only if sufficient funds exist, otherwise raises ValueError("Insufficient funds"); returns the new balance when successfulWhat does this code print?
class Counter:
count = 0
def __init__(self):
Counter.count += 1
self.id = Counter.count
a = Counter()
b = Counter()
print(a.count, b.count, a.id, b.id)The SavingsAccount should inherit from BankAccount and add an interest_rate. But the code crashes. Fix it so the tests pass.
Create a Book class with:
__init__(self, title: str, author: str, pages: int)__str__ returning "<title> by <author>"__repr__ returning "Book('<title>', '<author>', <pages>)"Create a Vector class representing a 2D vector:
__init__(self, x, y)__add__(self, other) returning a new Vector with component-wise addition__eq__(self, other) returning True if both components match__repr__ returning "Vector(<x>, <y>)"What does this code print?
class A:
def greet(self):
return "Hello from A"
class B(A):
def greet(self):
return "Hello from B"
class C(A):
pass
class D(B, C):
pass
d = D()
print(d.greet())
print(D.__mro__[1].__name__)This Temperature class uses a property to convert between Celsius and Fahrenheit, but the property setter is broken. Fix the code so setting fahrenheit correctly updates the stored Celsius value.
Refactor this class into a dataclass. The dataclass should automatically generate __init__, __repr__, and __eq__. Keep the full_name property.
Implement two classes demonstrating composition:
Engine(horsepower: int) with a method start() returning "Engine (<hp>hp) started"Car(make: str, engine: Engine) with a method start() returning "<make>: <engine.start()>"The Car delegates to its Engine -- it does not inherit from it.
What does this code print?
import math
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return round(math.pi * self.r ** 2, 2)
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
shapes = [Circle(5), Rectangle(4, 6), Circle(1)]
print(sum(s.area() for s in shapes))This Playlist class has two bugs. len() returns the wrong value and equality comparison crashes. Fix both.
The two shape classes share a duplicated describe() method. Refactor by:
1. Creating a Shape base class with describe(self) that returns "<class name>: area = <self.area()>"
2. Making Circle and Square inherit from Shape
3. Remove the duplicated describe methods from the subclasses