Chapter Practice Arena
All ChaptersObject-Oriented Programming Problems
Targeted practice challenges specifically curated for this chapter. Inspect hints, verify outputs, and check Pythonic solutions.
Difficulty:
Chapter:
Showing 6 challenges · 22 total · Page 1 of 4
Create a Counter class initialized with value 0. Add an increment() method that increases value by one. Call it twice and print the final value.
Starter Code
class Counter:
def __init__(self):
self.value = 0
# Define increment() here
pass
counter = Counter()
counter.increment()
counter.increment()
print(counter.value)Expected Output:2
Create a BankAccount class that accepts an initial balance and exposes it through a read-only balance property. Add a deposit(amount) method that accepts only positive amounts. Starting with 100, deposit 25 and print the balance.
Starter Code
class BankAccount:
def __init__(self, balance):
# Store the initial balance.
pass
# Define a read-only balance property.
def deposit(self, amount):
# Validate and add the deposit.
pass
account = BankAccount(100)
account.deposit(25)
print(account.balance)Expected Output:125
Define a Rectangle dataclass with width and height fields. Use __post_init__() to raise ValueError if either dimension is less than or equal to zero. Create Rectangle(4, 5) and print it.
Starter Code
from dataclasses import dataclass # Define Rectangle with width and height. # Validate both dimensions in __post_init__(). print(Rectangle(4, 5))
Expected Output:Rectangle(width=4, height=5)
Create a Product class whose initializer stores name and price. Create a product named "Pen" with price 10, then print the name and price on separate lines.
Starter Code
class Product:
def __init__(self, name, price):
# Store both attributes
pass
product = Product("Pen", 10)
# Print name and priceExpected Output:Pen
10
Create a Book class whose initializer accepts a title and stores it in self.title. Create a Book instance with the title "Dune" and print its title.
Starter Code
class Book:
# Define the initializer
pass
book = Book("Dune")
print(book.title)Expected Output:Dune
Create a Circle class that stores radius and exposes a diameter property returning radius multiplied by 2. Create Circle(3) and print its diameter.
Starter Code
class Circle:
def __init__(self, radius):
self.radius = radius
# Define the diameter property here.
circle = Circle(3)
# Print the diameter.Expected Output:6