Classes & Objects: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Define a class called Dog with nothing in it, create two objects from it, and print both.
Create a Dog object and give it a name and breed after it exists, then print them.
Give Dog an __init__ method that takes a name, and create two dogs with different names.
Give Dog a name, breed and age, and print a sentence describing one.
Explain self by showing what it refers to: print self inside __init__ and compare it with the object outside.
Add a method bark() to Dog that prints a message using the dog's own name.
Add a method that takes a parameter as well as self.
Write a method that changes an attribute, and show the object before and after.
Write a method that returns a calculated value rather than printing it.
Show that two objects of the same class hold completely separate data.
Give __init__ default values so some arguments become optional.
Use type() and isinstance() on your own objects.
Print an object's __dict__ to see its attributes as a dictionary.
Use hasattr(), getattr() and setattr() to work with attributes by name.
Add a class attribute shared by every object, and show it is the same for all of them.
Change a class attribute and show that every existing object sees the change.
Use a class attribute to count how many objects have been created.
Add __str__ so print(object) shows something readable.
Add __repr__ and show where it is used instead of __str__.
Show that __repr__ alone is enough, because __str__ falls back to it.
Show that two objects with identical data are not equal by default, then fix it with __eq__.
Add __len__ so len() works on your object.
Write a method that calls another method on the same object.
Write a class with a docstring and documented methods, then read them back.
Delete an attribute with del and show what happens when it is read afterwards.
Build a BankAccount whose deposit and withdraw methods enforce their own rules.
Validate arguments inside __init__ so a badly formed object cannot exist at all.
Use a class attribute as a constant that the methods rely on.
Build a class that holds a list, and add to it through a method.
Put objects in a list, loop over them, and total a field.
Sort a list of objects by an attribute, using the (value, name) trick since sorted(key=…) is Topic 19.
Store objects in a dictionary keyed by an identifier and look them up.
Make objects usable in a set by defining both __eq__ and __hash__.
Return self from methods so calls can be chained.
Add a @staticmethod — a function that belongs with the class but needs no object.
Add a @classmethod that builds an object a different way — an alternative constructor.
Use a class method to manage a class attribute.
Convert objects to dictionaries, save them as JSON, and rebuild them.
Read a CSV straight into objects and report on them.
Build a Stack class with push, pop, peek and is_empty.
Build a Queue class and contrast it with the stack.
Build a Point class with a distance method and a class method for the origin.
Build a Timer class that accumulates elapsed time across several runs.
Group objects with defaultdict and count them with Counter.
Use a class attribute to hold a registry of every object created.
Build a class whose method raises a custom exception, and handle it at the call site.
Pass objects into functions and show that changes inside the function are visible outside.
Show that copying an object needs copy.deepcopy when it holds a mutable attribute.
Build a class that wraps a dictionary and offers a tidier interface to it.
Build a Matrix class supporting addition through a method, with validation.
Model a library book with borrow and return behaviour and a copy count.
Model a shopping cart that holds product objects and totals itself.
Model a playing card and a deck that can be shuffled and dealt.
Model a student gradebook where the class holds student objects.
Model a bank account that keeps its own transaction log.
Model a traffic light as a small state machine.
Model a parking lot with numbered spaces and vehicle objects.
Model a to-do list with task objects that can be completed and filtered.
Model an employee payroll with a class method that builds employees from records.
Model a text analyser as a class that computes its statistics once and reuses them.
Model a dice game where the die is an object with its own history.
Model a contact with validation and a formatted display.
Model a vending machine that tracks stock and money.
Model a password checker as a class with the rules as class data.
Model a playlist that can shuffle, find and total its duration.
Model a quiz where each question is an object that can check its own answer.
Model a recipe that can scale its ingredient quantities.
Model a temperature reading with conversions and comparison behaviour.
Model a voting machine where candidates are objects and the machine enforces the rules.
Model a simple event log where each entry is an object and the log summarises itself.
This raises TypeError. Explain what Python is complaining about and fix it.
class Dog:
def __init__(self, name):
self.name = name
def bark():
print("Woof!")
rex = Dog("Rex")
rex.bark()Every dog ends up sharing one list of tricks. Explain why and fix it.
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def learn(self, trick):
self.tricks.append(trick)
rex = Dog("Rex")
bella = Dog("Bella")
rex.learn("sit")
bella.learn("roll over")
print(rex.tricks)
print(bella.tricks)This counter never goes past 1. Find the bug.
class User:
count = 0
def __init__(self, name):
self.name = name
self.count += 1
a = User("Asha")
b = User("Raj")
c = User("Meera")
print(f"User.count = {User.count}")
print(f"a.count = {a.count}")Explain why returning a value from __init__ fails, and what to use instead.
Explain why two objects with identical data are not equal, and what == does by default.
Defining __eq__ breaks putting objects in a set. Explain and fix.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
points = {Point(1, 2)}Show that assigning through an instance hides the class attribute for that object only.
Show why attributes created outside __init__ lead to objects of the same class with different shapes.
Explain what this prints and why calling a method without parentheses is a silent bug.
class Account:
def __init__(self, balance):
self.balance = balance
def is_overdrawn(self):
return self.balance < 0
account = Account(-50)
if account.is_overdrawn:
print("overdrawn!")
account2 = Account(1000)
if account2.is_overdrawn:
print("also overdrawn?!")Show that giving a mutable object to a constructor lets outside code change it afterwards.
Show the three mistakes people make when writing __str__.
Show when is and == differ for objects, and which to use.
Show how a typo in an attribute name creates a new attribute instead of failing.
Show what happens when __eq__ and __hash__ disagree.
Argue when a class is the wrong choice, and show the simpler alternatives.
Build a Bank System with Account objects, a Bank that holds them, custom exceptions and transfers between accounts.
Build a Library System with Book and Member objects and a Library that enforces borrowing limits.
Build an Inventory System with Item objects, JSON persistence and a low-stock report.
Build a Student Grade System with Student and Course objects and a full statistics report.
Build a Shopping System with Product, CartLine and Cart objects, discounts and a printed receipt.
Build a Card Game where Card, Deck and Player objects play several rounds of highest-card-wins.
Build a Task Manager with Task objects, priorities, filtering and file persistence.
Build a Contact Book with Contact objects, validation, search and CSV persistence.
Build a Vending Machine with Slot objects, coin handling and a sales report.
Build a Simulation where Sensor objects generate readings and a Monitor object summarises and flags them.
Explain what self actually is, why Python makes it explicit, and what happens without it.
Compare class attributes and instance attributes across creation, storage, lookup and the traps.
Decide between a function, a dictionary, a namedtuple and a class. Give the test and demonstrate all four.
Explain the dunder protocol: what these methods are, why Python calls them, and which ones a well-made class defines.
Capstone. Build a Class Toolkit Report — one program demonstrating __init__, validation, instance and class attributes, instance/static/class methods, __str__, __repr__, __eq__, __hash__, __len__, objects in every collection type, sorting, copying and JSON persistence.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session