Classes & Objects — Practice Questions
50 questions. Try each one yourself before checking the answer.
Define an empty class Dog (using pass), create an instance of it, and print its type().
Define a Dog class with an __init__ constructor that sets an instance variable name. Create a dog and print its name.
Define a Dog class whose __init__ sets both name and age. Create a dog and print both attributes.
Add a method bark() to the Dog class that prints "Woof!". Call it on an instance.
Add a method describe() to Dog that uses self.name to print "<name> is a good dog."
Create TWO Dog instances with different names, and show that each keeps its own independent name.
Give Dog's constructor a default value for age (0), so it can be created with or without an age.
Add a method have_birthday() to Dog that increases self.age by 1. Call it and print the new age.
Add a method is_adult() to Dog that RETURNS True if self.age >= 2, False otherwise.
Given my_dog = Dog("Rex", 3), print isinstance(my_dog, Dog) and type(my_dog).
Define a Rectangle class with width and height, plus methods area() and perimeter() that each return their respective calculation.
Define a Dog class with a CLASS attribute species = "Canis familiaris" (shared by all dogs), and an instance attribute name. Print both from an instance.
Using the Dog class from Q12, create two dogs and show that species is the SAME value for both, accessible either through an instance or through the class itself.
Define a BankAccount class with a balance instance attribute and a deposit(amount) method that adds to it.
Add a withdraw(amount) method to BankAccount (from Q14) that only subtracts if there are sufficient funds, returning True/False to indicate success.
Define a Student class with a grades list attribute (starting empty), and an add_grade(score) method that appends to it.
Using the Student class from Q16, create two students and confirm that each has its OWN independent grades list, not a shared one.
Add an average() method to Student (from Q16) that returns the average of self.grades, or 0 if there are none.
Define a Car class with make, model, and a mileage attribute starting at 0, plus a drive(distance) method that adds to mileage.
Create two Dog instances with the SAME name and age. Print whether dog1 == dog2 and dog1 is dog2, explaining the result in a comment.
Build a Book class with title, author, and is_checked_out (starting False), plus checkout() and return_book() methods that toggle it.
Build an Employee class with name and hourly_rate, plus a calculate_pay(hours) method returning hours * hourly_rate.
Build a Counter class that tracks HOW MANY instances have been created, using a class attribute incremented inside __init__.
Build a Person class with name and age, plus a have_birthday() method that increments age and prints a birthday message using self.name.
Build a ShoppingCart class with an items dict (item -> price), plus add_item(name, price) and total() methods.
Build a Temperature class storing a value in Celsius, plus a to_fahrenheit() method converting it.
Build a Timer class with seconds_elapsed starting at 0, plus a tick(seconds) method that adds time, and a formatted() method returning MM:SS.
Build a TrafficLight class starting at "red", with a next_state() method cycling red -> green -> yellow -> red.
The following code raises a TypeError when calling bark(). Find and fix the bug.
class Dog:
def __init__(self, name):
self.name = name
def bark():
print("Woof!")
my_dog = Dog("Rex")
my_dog.bark()Build a Product class with name and price, plus a __str__ method returning a nicely formatted description, and print an instance directly.
Demonstrate the classic mutable-CLASS-attribute bug: a list defined at the class level (not inside __init__) ends up SHARED across every instance. Show the bug and the fix.
Demonstrate the mutable-default-argument bug (from the Functions module) inside a constructor: __init__(self, items=[]) and the None-sentinel fix.
Build a QueryBuilder class where methods like select() and where() each return self, enabling method chaining (builder.select("*").where("id=1")).
Add an alternate constructor to a Date class using @classmethod: Date.from_string("2024-06-15") should parse the string and return a Date instance.
Add a @staticmethod is_valid_score(score) to a Student class — a utility check that doesn't need self or any particular instance.
Build a BankAccount whose __init__ raises a ValueError if the starting balance is negative, tying exception handling back into class design.
Build a BankAccount using a "private-by-convention" attribute _balance (leading underscore), with a get_balance() method, demonstrating that Python doesn't truly enforce privacy.
Demonstrate that my_dog.bark() is really just shorthand for Dog.bark(my_dog), by calling the method both ways and showing identical output.
Build a Playlist class with a songs list and methods add_song(), remove_song(), and shuffle() (using the random module).
The following code doesn't raise an error, but total_created never goes above 1 no matter how many instances are made. Find and fix the bug.
class Counter:
total_created = 0
def __init__(self):
total_created = Counter.total_created + 1
c1 = Counter()
c2 = Counter()
print(Counter.total_created)Build a full BankAccount class: constructor with starting balance, deposit(), withdraw() (with insufficient-funds protection), and a transaction_history list logging every operation.
Build a Student "Report Card" class: name, a dict of subject: score, an add_score() method, and a report() method printing every subject plus the overall average.
Build a Library mini-system: a Book class (title, is_checked_out) and a Library class holding a list of Books with checkout(title) and return_book(title) methods.
Build a Task class (description, is_done) and a TodoList class managing a list of Tasks with add_task(), complete_task(), and show_pending().
Build an Employee "Payroll" class with name, hourly_rate, hours_worked, and a net_pay() method that deducts a flat 10% tax from the gross pay.
Explain what self actually IS (just the instance the method was called on), demonstrating it by printing self inside a method and comparing it to the original variable with is.
A classic interview question: "what's the difference between an instance attribute and a class attribute, and when does mixing them cause bugs?" Answer with the shared-mutable-default gotcha as the concrete example.
Explain the difference between an instance method, a @classmethod, and a @staticmethod, demonstrating all three on the same class.
Explain why Python's default == for objects checks identity, not attribute equality, and what problem that would cause if you tried to use custom objects as dictionary keys expecting "same values = same key."
Build a "Class Mastery Report" — the most complete demonstration in this module. Design a Product class with: instance attributes, a class attribute tracking total products created, a regular method, a @classmethod alternate constructor (from_string), and a @staticmethod validator — then create a few products and print a full labeled report.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session