Python · Object Oriented Programming

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.

Q1Defining ClassesEasyMust Do

Define a class called Dog with nothing in it, create two objects from it, and print both.

Q2AttributesEasy

Create a Dog object and give it a name and breed after it exists, then print them.

Q3__init__EasyMust Do

Give Dog an __init__ method that takes a name, and create two dogs with different names.

Q4__init__Easy

Give Dog a name, breed and age, and print a sentence describing one.

Q5selfEasyMust Do

Explain self by showing what it refers to: print self inside __init__ and compare it with the object outside.

Q6MethodsEasyMust Do

Add a method bark() to Dog that prints a message using the dog's own name.

Q7MethodsEasy

Add a method that takes a parameter as well as self.

Q8MethodsEasyMust Do

Write a method that changes an attribute, and show the object before and after.

Q9MethodsEasy

Write a method that returns a calculated value rather than printing it.

Q10ObjectsEasy

Show that two objects of the same class hold completely separate data.

Q11__init__Easy

Give __init__ default values so some arguments become optional.

Q12type & isinstanceEasy

Use type() and isinstance() on your own objects.

Q13__dict__Easy

Print an object's __dict__ to see its attributes as a dictionary.

Q14AttributesEasy

Use hasattr(), getattr() and setattr() to work with attributes by name.

Q15Class AttributesEasyMust Do

Add a class attribute shared by every object, and show it is the same for all of them.

Q16Class AttributesEasy

Change a class attribute and show that every existing object sees the change.

Q17Class AttributesEasy

Use a class attribute to count how many objects have been created.

Q18__str__EasyMust Do

Add __str__ so print(object) shows something readable.

Q19__repr__Easy

Add __repr__ and show where it is used instead of __str__.

Q20__repr__Easy

Show that __repr__ alone is enough, because __str__ falls back to it.

Q21__eq__EasyMust Do

Show that two objects with identical data are not equal by default, then fix it with __eq__.

Q22__len__Easy

Add __len__ so len() works on your object.

Q23MethodsEasy

Write a method that calls another method on the same object.

Q24DocstringsEasy

Write a class with a docstring and documented methods, then read them back.

Q25AttributesEasy

Delete an attribute with del and show what happens when it is read afterwards.

Q26ValidationMediumMust Do

Build a BankAccount whose deposit and withdraw methods enforce their own rules.

Q27ValidationMedium

Validate arguments inside __init__ so a badly formed object cannot exist at all.

Q28Class AttributesMedium

Use a class attribute as a constant that the methods rely on.

Q29Mutable AttributesMediumMust Do

Build a class that holds a list, and add to it through a method.

Q30Objects in ListsMedium

Put objects in a list, loop over them, and total a field.

Q31Sorting ObjectsMediumMust Do

Sort a list of objects by an attribute, using the (value, name) trick since sorted(key=…) is Topic 19.

Q32Objects in DictsMedium

Store objects in a dictionary keyed by an identifier and look them up.

Q33__eq__ & __hash__MediumMust Do

Make objects usable in a set by defining both __eq__ and __hash__.

Q34Method ChainingMedium

Return self from methods so calls can be chained.

Q35@staticmethodMedium

Add a @staticmethod — a function that belongs with the class but needs no object.

Q36@classmethodMediumMust Do

Add a @classmethod that builds an object a different way — an alternative constructor.

Q37@classmethodMedium

Use a class method to manage a class attribute.

Q38Objects & JSONMedium

Convert objects to dictionaries, save them as JSON, and rebuild them.

Q39Objects & CSVMedium

Read a CSV straight into objects and report on them.

Q40DesignMediumMust Do

Build a Stack class with push, pop, peek and is_empty.

Q41DesignMedium

Build a Queue class and contrast it with the stack.

Q42DesignMedium

Build a Point class with a distance method and a class method for the origin.

Q43DesignMedium

Build a Timer class that accumulates elapsed time across several runs.

Q44Objects in CollectionsMedium

Group objects with defaultdict and count them with Counter.

Q45Class AttributesMedium

Use a class attribute to hold a registry of every object created.

Q46ValidationMedium

Build a class whose method raises a custom exception, and handle it at the call site.

Q47Objects as ArgumentsMedium

Pass objects into functions and show that changes inside the function are visible outside.

Q48copyMedium

Show that copying an object needs copy.deepcopy when it holds a mutable attribute.

Q49DesignMedium

Build a class that wraps a dictionary and offers a tidier interface to it.

Q50DesignMedium

Build a Matrix class supporting addition through a method, with validation.

Q51Real-WorldMedium

Model a library book with borrow and return behaviour and a copy count.

Q52Real-WorldMediumMust Do

Model a shopping cart that holds product objects and totals itself.

Q53Class AttributesMedium

Model a playing card and a deck that can be shuffled and dealt.

Q54Real-WorldMediumMust Do

Model a student gradebook where the class holds student objects.

Q55Real-WorldMedium

Model a bank account that keeps its own transaction log.

Q56DesignMediumMust Do

Model a traffic light as a small state machine.

Q57Real-WorldMedium

Model a parking lot with numbered spaces and vehicle objects.

Q58Real-WorldMedium

Model a to-do list with task objects that can be completed and filtered.

Q59Real-WorldMedium

Model an employee payroll with a class method that builds employees from records.

Q60MethodsMedium

Model a text analyser as a class that computes its statistics once and reuses them.

Q61Real-WorldMedium

Model a dice game where the die is an object with its own history.

Q62ValidationMediumMust Do

Model a contact with validation and a formatted display.

Q63Real-WorldMedium

Model a vending machine that tracks stock and money.

Q64ValidationMedium

Model a password checker as a class with the rules as class data.

Q65Real-WorldMedium

Model a playlist that can shuffle, find and total its duration.

Q66MethodsMedium

Model a quiz where each question is an object that can check its own answer.

Q67Real-WorldMedium

Model a recipe that can scale its ingredient quantities.

Q68@classmethodMediumMust Do

Model a temperature reading with conversions and comparison behaviour.

Q69Real-WorldMedium

Model a voting machine where candidates are objects and the machine enforces the rules.

Q70Objects in CollectionsMedium

Model a simple event log where each entry is an object and the log summarises itself.

Q71selfHardMust Do

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()
Q72Class AttributesHardMust Do

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)
Q73Class AttributesHard

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}")
Q74__init__Hard

Explain why returning a value from __init__ fails, and what to use instead.

Q75__eq__Hard

Explain why two objects with identical data are not equal, and what == does by default.

Q76__hash__HardMust Do

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)}
Q77Class AttributesHard

Show that assigning through an instance hides the class attribute for that object only.

Q78DesignHard

Show why attributes created outside __init__ lead to objects of the same class with different shapes.

Q79MethodsHard

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?!")
Q80MutabilityHard

Show that giving a mutable object to a constructor lets outside code change it afterwards.

Q81__str__Hard

Show the three mistakes people make when writing __str__.

Q82IdentityHard

Show when is and == differ for objects, and which to use.

Q83AttributesHard

Show how a typo in an attribute name creates a new attribute instead of failing.

Q84__eq__Hard

Show what happens when __eq__ and __hash__ disagree.

Q85DesignHard

Argue when a class is the wrong choice, and show the simpler alternatives.

Q86Mini-ProjectMini-ProjectMust Do

Build a Bank System with Account objects, a Bank that holds them, custom exceptions and transfers between accounts.

Q87Mini-ProjectMini-Project

Build a Library System with Book and Member objects and a Library that enforces borrowing limits.

Q88Mini-ProjectMini-Project

Build an Inventory System with Item objects, JSON persistence and a low-stock report.

Q89Mini-ProjectMini-ProjectMust Do

Build a Student Grade System with Student and Course objects and a full statistics report.

Q90Mini-ProjectMini-Project

Build a Shopping System with Product, CartLine and Cart objects, discounts and a printed receipt.

Q91Mini-ProjectMini-Project

Build a Card Game where Card, Deck and Player objects play several rounds of highest-card-wins.

Q92Mini-ProjectMini-Project

Build a Task Manager with Task objects, priorities, filtering and file persistence.

Q93Mini-ProjectMini-Project

Build a Contact Book with Contact objects, validation, search and CSV persistence.

Q94Mini-ProjectMini-Project

Build a Vending Machine with Slot objects, coin handling and a sales report.

Q95Mini-ProjectMini-Project

Build a Simulation where Sensor objects generate readings and a Monitor object summarises and flags them.

Q96InterviewInterview

Explain what self actually is, why Python makes it explicit, and what happens without it.

Q97Class AttributesInterview

Compare class attributes and instance attributes across creation, storage, lookup and the traps.

Q98DesignInterview

Decide between a function, a dictionary, a namedtuple and a class. Give the test and demonstrate all four.

Q99Dunder MethodsInterview

Explain the dunder protocol: what these methods are, why Python calls them, and which ones a well-made class defines.

Q100CapstoneInterviewMust Do

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