Python · Object Oriented Programming

Classes & Objects — Practice Questions

50 questions. Try each one yourself before checking the answer.

Q1ClassesEasy

Define an empty class Dog (using pass), create an instance of it, and print its type().

Q2ConstructorsEasy

Define a Dog class with an __init__ constructor that sets an instance variable name. Create a dog and print its name.

Q3Instance VariablesEasy

Define a Dog class whose __init__ sets both name and age. Create a dog and print both attributes.

Q4MethodsEasy

Add a method bark() to the Dog class that prints "Woof!". Call it on an instance.

Q5selfEasy

Add a method describe() to Dog that uses self.name to print "<name> is a good dog."

Q6Multiple InstancesEasy

Create TWO Dog instances with different names, and show that each keeps its own independent name.

Q7Default ArgumentsEasy

Give Dog's constructor a default value for age (0), so it can be created with or without an age.

Q8Modifying StateEasy

Add a method have_birthday() to Dog that increases self.age by 1. Call it and print the new age.

Q9Methods Returning ValuesEasy

Add a method is_adult() to Dog that RETURNS True if self.age >= 2, False otherwise.

Q10isinstance()Easy

Given my_dog = Dog("Rex", 3), print isinstance(my_dog, Dog) and type(my_dog).

Q11MethodsMedium

Define a Rectangle class with width and height, plus methods area() and perimeter() that each return their respective calculation.

Q12Class AttributesMedium

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.

Q13Class AttributesMedium

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.

Q14Methods with ParametersMedium

Define a BankAccount class with a balance instance attribute and a deposit(amount) method that adds to it.

Q15Methods with ParametersMedium

Add a withdraw(amount) method to BankAccount (from Q14) that only subtracts if there are sufficient funds, returning True/False to indicate success.

Q16Mutable Instance AttributesMedium

Define a Student class with a grades list attribute (starting empty), and an add_grade(score) method that appends to it.

Q17Mutable Instance AttributesMedium

Using the Student class from Q16, create two students and confirm that each has its OWN independent grades list, not a shared one.

Q18Methods Returning Computed ValuesMedium

Add an average() method to Student (from Q16) that returns the average of self.grades, or 0 if there are none.

Q19Real-WorldMedium

Define a Car class with make, model, and a mileage attribute starting at 0, plus a drive(distance) method that adds to mileage.

Q20Object IdentityMedium

Create two Dog instances with the SAME name and age. Print whether dog1 == dog2 and dog1 is dog2, explaining the result in a comment.

Q21Real-WorldMedium

Build a Book class with title, author, and is_checked_out (starting False), plus checkout() and return_book() methods that toggle it.

Q22Real-WorldMedium

Build an Employee class with name and hourly_rate, plus a calculate_pay(hours) method returning hours * hourly_rate.

Q23Class AttributesMedium

Build a Counter class that tracks HOW MANY instances have been created, using a class attribute incremented inside __init__.

Q24Real-WorldMedium

Build a Person class with name and age, plus a have_birthday() method that increments age and prints a birthday message using self.name.

Q25Real-WorldMedium

Build a ShoppingCart class with an items dict (item -> price), plus add_item(name, price) and total() methods.

Q26Real-WorldMedium

Build a Temperature class storing a value in Celsius, plus a to_fahrenheit() method converting it.

Q27Real-WorldMedium

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.

Q28Real-WorldMedium

Build a TrafficLight class starting at "red", with a next_state() method cycling red -> green -> yellow -> red.

Q29DebuggingMedium

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()
Q30FormattingMedium

Build a Product class with name and price, plus a __str__ method returning a nicely formatted description, and print an instance directly.

Q31Class Attribute PitfallHard

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.

Q32ConstructorsHard

Demonstrate the mutable-default-argument bug (from the Functions module) inside a constructor: __init__(self, items=[]) and the None-sentinel fix.

Q33Method ChainingHard

Build a QueryBuilder class where methods like select() and where() each return self, enabling method chaining (builder.select("*").where("id=1")).

Q34classmethodHard

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.

Q35staticmethodHard

Add a @staticmethod is_valid_score(score) to a Student class — a utility check that doesn't need self or any particular instance.

Q36Constructors with ValidationHard

Build a BankAccount whose __init__ raises a ValueError if the starting balance is negative, tying exception handling back into class design.

Q37Encapsulation ConventionHard

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.

Q38Calling Methods ExplicitlyHard

Demonstrate that my_dog.bark() is really just shorthand for Dog.bark(my_dog), by calling the method both ways and showing identical output.

Q39Real-WorldHard

Build a Playlist class with a songs list and methods add_song(), remove_song(), and shuffle() (using the random module).

Q40DebuggingHard

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)
Q41Mini-ProjectMini-Project

Build a full BankAccount class: constructor with starting balance, deposit(), withdraw() (with insufficient-funds protection), and a transaction_history list logging every operation.

Q42Mini-ProjectMini-Project

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.

Q43Mini-ProjectMini-Project

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.

Q44Mini-ProjectMini-Project

Build a Task class (description, is_done) and a TodoList class managing a list of Tasks with add_task(), complete_task(), and show_pending().

Q45Mini-ProjectMini-Project

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.

Q46InterviewInterview

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.

Q47InterviewInterview

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.

Q48InterviewInterview

Explain the difference between an instance method, a @classmethod, and a @staticmethod, demonstrating all three on the same class.

Q49InterviewInterview

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."

Q50CapstoneInterview

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