Class and Objects Practice
Define classes, create objects and work with instance attributes and methods.
1
Define a Class and Create an Object
Easy
Write a class Student with attribute name. Create an object with name from input and print it.
Input Format
A single line containing a name.
Output Format
Print the student name.
Sample Test Cases
|
Sample Input 1
Ravi |
Sample Output 1
Ravi |
|
Sample Input 2
Bob |
Sample Output 2
Bob |
|
Sample Input 3
Sam |
Sample Output 3
Sam |
2
Object with Multiple Attributes
Easy
Write a class Laptop with brand and price attributes. Read both, create an object, and print both.
Input Format
First line: brand. Second line: price.
Output Format
Print 'Brand: [brand]' and 'Price: [price]' on separate lines.
Sample Test Cases
|
Sample Input 1
Dell 55000 |
Sample Output 1
Brand: Dell Price: 55000 |
|
Sample Input 2
HP 40000 |
Sample Output 2
Brand: HP Price: 40000 |
|
Sample Input 3
Lenovo 60000 |
Sample Output 3
Brand: Lenovo Price: 60000 |
3
Call a Method on an Object
Easy
Write a class Animal with a method sound() that prints 'Some sound'. Create an object and call sound().
Input Format
No input.
Output Format
Print 'Some sound'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Some sound |
|
Sample Input 2
|
Sample Output 2
Some sound |
|
Sample Input 3
|
Sample Output 3
Some sound |
4
Access Object Attributes
Easy
Write a class Person with name and age. Read both, create an object, and print 'name is age years old'.
Input Format
First line: name. Second line: age.
Output Format
Print the sentence.
Sample Test Cases
|
Sample Input 1
Alice 25 |
Sample Output 1
Alice is 25 years old |
|
Sample Input 2
Bob 30 |
Sample Output 2
Bob is 30 years old |
|
Sample Input 3
Kid 5 |
Sample Output 3
Kid is 5 years old |
5
Create Multiple Objects
Easy
Write a class Point with x and y. Create two objects (1,2) and (3,4) and print both.
Input Format
No input.
Output Format
Print both points as (x, y), one per line.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
(1, 2) (3, 4) |
|
Sample Input 2
|
Sample Output 2
(1, 2) (3, 4) |
|
Sample Input 3
|
Sample Output 3
(1, 2) (3, 4) |
6
Object Method with Argument
Easy
Write a class Dog with a method run(speed) that prints 'Running at [speed] km/h'.
Input Format
A single line containing the speed.
Output Format
Print the running message.
Sample Test Cases
|
Sample Input 1
20 |
Sample Output 1
Running at 20 km/h |
|
Sample Input 2
50 |
Sample Output 2
Running at 50 km/h |
|
Sample Input 3
10 |
Sample Output 3
Running at 10 km/h |
7
Modify Object Attribute
Easy
Write a class Phone with attribute battery. Create an object with battery 100, read a new value, update it, and print it.
Input Format
A single line containing the new battery value.
Output Format
Print the updated battery.
Sample Test Cases
|
Sample Input 1
75 |
Sample Output 1
75 |
|
Sample Input 2
50 |
Sample Output 2
50 |
|
Sample Input 3
100 |
Sample Output 3
100 |
8
Print Attribute via Method
Easy
Write a class Movie with title attribute and a method get_title() that returns it.
Input Format
A single line containing a movie title.
Output Format
Print the title.
Sample Test Cases
|
Sample Input 1
Inception |
Sample Output 1
Inception |
|
Sample Input 2
Titanic |
Sample Output 2
Titanic |
|
Sample Input 3
Jaws |
Sample Output 3
Jaws |
9
Two Objects with Different Values
Easy
Write a class Fruit with name and color. Create objects apple/red and banana/yellow and print each as 'name is color'.
Input Format
No input.
Output Format
Print both descriptions, one per line.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
apple is red banana is yellow |
|
Sample Input 2
|
Sample Output 2
apple is red banana is yellow |
|
Sample Input 3
|
Sample Output 3
apple is red banana is yellow |
10
Simple Class with Display
Easy
Write a class Teacher with subject attribute and a method show() that prints the subject.
Input Format
A single line containing a subject.
Output Format
Print the subject.
Sample Test Cases
|
Sample Input 1
Mathematics |
Sample Output 1
Mathematics |
|
Sample Input 2
Science |
Sample Output 2
Science |
|
Sample Input 3
Maths |
Sample Output 3
Maths |
1
Class with List Attribute
Medium
Write a class Classroom with students list and a method add_student(name). Add 3 students and print the list.
Input Format
Three lines, each containing a student name.
Output Format
Print the list of students.
Sample Test Cases
|
Sample Input 1
Alice Bob Carol |
Sample Output 1
['Alice', 'Bob', 'Carol'] |
|
Sample Input 2
X Y Z |
Sample Output 2
['X', 'Y', 'Z'] |
|
Sample Input 3
1 2 3 |
Sample Output 3
['1', '2', '3'] |
2
Method That Returns a Value
Medium
Write a class Rectangle with length and breadth and a method area() that returns length * breadth.
Input Format
A single line containing two space-separated integers.
Output Format
Print the area.
Sample Test Cases
|
Sample Input 1
5 8 |
Sample Output 1
40 |
|
Sample Input 2
10 20 |
Sample Output 2
200 |
|
Sample Input 3
3 3 |
Sample Output 3
9 |
3
Object as Method Argument
Medium
Write a class Point with x, y and a method distance_to(other) that returns the Manhattan distance |x1-x2| + |y1-y2|.
Input Format
First line: x and y of point 1. Second line: x and y of point 2.
Output Format
Print the Manhattan distance.
Sample Test Cases
|
Sample Input 1
1 2 4 6 |
Sample Output 1
7 |
|
Sample Input 2
0 0 3 4 |
Sample Output 2
7 |
|
Sample Input 3
-1 -1 1 1 |
Sample Output 3
4 |
4
Class with Class Attribute
Medium
Write a class Animal with class attribute kingdom = 'Animalia'. Read an animal name, create an object, and print 'name belongs to Animalia'.
Input Format
A single line containing an animal name.
Output Format
Print the sentence.
Sample Test Cases
|
Sample Input 1
Lion |
Sample Output 1
Lion belongs to Animalia |
|
Sample Input 2
Tiger |
Sample Output 2
Tiger belongs to Animalia |
|
Sample Input 3
|
Sample Output 3
belongs to Animalia |
5
Check Object Equality by Attribute
Medium
Write a class Song with title attribute. Read two titles, create two objects, and print 'Same' if titles are equal else 'Different'.
Input Format
First line: title 1. Second line: title 2.
Output Format
Print Same or Different.
Sample Test Cases
|
Sample Input 1
Believer Believer |
Sample Output 1
Same |
|
Sample Input 2
Hello Hi |
Sample Output 2
Different |
|
Sample Input 3
A A |
Sample Output 3
Same |
6
Object with Default Attribute
Medium
Write a class Bike with color attribute defaulting to 'black'. Read a color, create an object, and print it. If empty input, print 'black'.
Input Format
A single line containing a color (may be empty).
Output Format
Print the bike color.
Sample Test Cases
|
Sample Input 1
red |
Sample Output 1
red |
|
Sample Input 2
blue |
Sample Output 2
blue |
|
Sample Input 3
|
Sample Output 3
black |
7
Nested Object — Address in Person
Medium
Write a class Address with city, and a class Person with name and an Address object. Read name and city, create objects, and print 'name lives in city'.
Input Format
First line: name. Second line: city.
Output Format
Print the sentence.
Sample Test Cases
|
Sample Input 1
Alice Delhi |
Sample Output 1
Alice lives in Delhi |
|
Sample Input 2
Bob Mumbai |
Sample Output 2
Bob lives in Mumbai |
|
Sample Input 3
Sam Goa |
Sample Output 3
Sam lives in Goa |
8
List of Objects
Medium
Write a class Player with name and score. Read N players, create objects in a list, and print the name of the highest scorer.
Input Format
First line: integer N. Next N lines: name and score space-separated.
Output Format
Print the name of the highest scorer.
Sample Test Cases
|
Sample Input 1
3 Virat 89 Rohit 64 Dhoni 45 |
Sample Output 1
Virat |
|
Sample Input 2
2 A 50 B 90 |
Sample Output 2
B |
|
Sample Input 3
2 X 70 Y 70 |
Sample Output 3
X |
9
Method Returning Multiple Values
Medium
Write a class Stats with a method min_max(lst) that returns the minimum and maximum of a list.
Input Format
First line: integer N. Second line: N space-separated integers.
Output Format
Print the minimum and maximum space-separated.
Sample Test Cases
|
Sample Input 1
5 9 2 7 1 5 |
Sample Output 1
1 9 |
|
Sample Input 2
3 5 1 9 |
Sample Output 2
1 9 |
|
Sample Input 3
1 7 |
Sample Output 3
7 7 |
10
Class with Static Method
Medium
Write a class MathUtils with a static method add(a, b) called on the class itself.
Input Format
A single line containing two space-separated integers.
Output Format
Print their sum.
Sample Test Cases
|
Sample Input 1
12 8 |
Sample Output 1
20 |
|
Sample Input 2
1 2 |
Sample Output 2
3 |
|
Sample Input 3
100 200 |
Sample Output 3
300 |
1
Library with List of Book Objects
Hard
Write a class Book with title and author, and a class Library with a list of Book objects and a method find(author) that prints all books by that author.
Input Format
First line: integer N. Next N lines: title and author. Last line: search author.
Output Format
Print titles of books by the search author, one per line.
Sample Test Cases
|
Sample Input 1
3 Python101 Guido CleanCode Robert DesignPatterns Erich |
Sample Output 1
Robert |
|
Sample Input 2
2 B1 E1 B2 E2 E1 |
Sample Output 2
B1 |
|
Sample Input 3
1 C1 G1 G1 |
Sample Output 3
C1 |
2
OOP — Employee Management
Hard
Write a class Employee with name, id, and salary, and a method yearly_salary() that returns salary * 12. Create 2 employees and print their yearly salaries.
Input Format
Two lines, each: name id salary space-separated.
Output Format
Print each employee's yearly salary on a new line.
Sample Test Cases
|
Sample Input 1
Alice 101 30000 Bob 102 25000 |
Sample Output 1
360000 300000 |
|
Sample Input 2
A 1 1000 B 2 2000 |
Sample Output 2
12000 24000 |
|
Sample Input 3
C 3 500 |
Sample Output 3
6000 |
3
OOP — Bank Transfer Between Accounts
Hard
Write a class BankAccount with balance and methods deposit(amount), withdraw(amount), and transfer(other, amount). Transfer 500 from A to B and print both balances.
Input Format
First line: initial balance of A. Second line: initial balance of B. Third line: transfer amount.
Output Format
Print 'A: [balance]' and 'B: [balance]' after transfer.
Sample Test Cases
|
Sample Input 1
1000 500 300 |
Sample Output 1
A: 700 B: 800 |
|
Sample Input 2
2000 1000 500 |
Sample Output 2
A: 1500 B: 1500 |
|
Sample Input 3
500 100 600 |
Sample Output 3
Insufficient balance |
4
OOP — School with Student Objects
Hard
Write a class Student with name and marks, and a class School that stores students and computes average marks.
Input Format
First line: integer N. Next N lines: name and marks.
Output Format
Print the average marks rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
3 Alice 80 Bob 70 Carol 90 |
Sample Output 1
80.00 |
|
Sample Input 2
2 A 100 B 50 |
Sample Output 2
75.00 |
|
Sample Input 3
3 X 10 Y 20 Z 30 |
Sample Output 3
20.00 |
5
Object Serialization Simulation
Hard
Write a class Record with name and value and a method to_dict() that returns {'name': ..., 'value': ...}. Read name and value and print the dict.
Input Format
First line: name. Second line: value.
Output Format
Print the dictionary representation.
Sample Test Cases
|
Sample Input 1
score 95 |
Sample Output 1
{'name': 'score', 'value': '95'}
|
|
Sample Input 2
key value |
Sample Output 2
{'name': 'key', 'value': 'value'}
|
|
Sample Input 3
a 1 |
Sample Output 3
{'name': 'a', 'value': '1'}
|
6
OOP — Traffic Light System
Hard
Write a class TrafficLight with state and a method change() that cycles Red -> Green -> Yellow -> Red. Start at Red, call change() 4 times and print the states.
Input Format
No input.
Output Format
Print the state after each call, one per line.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Green Yellow Red Green |
|
Sample Input 2
|
Sample Output 2
Green Yellow Red Green |
|
Sample Input 3
|
Sample Output 3
Green Yellow Red Green |
7
OOP — Currency Converter
Hard
Write a class Currency with amount and a method convert(rate) that returns amount * rate.
Input Format
First line: amount. Second line: rate.
Output Format
Print the converted value rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
100 74.5 |
Sample Output 1
7450.00 |
|
Sample Input 2
1 1 |
Sample Output 2
1.00 |
|
Sample Input 3
50 80 |
Sample Output 3
4000.00 |
8
OOP — Team with Player Objects
Hard
Write a class Player with name and runs, and a class Team that holds players and a method top_scorer() returning the player with max runs.
Input Format
First line: integer N. Next N lines: name and runs.
Output Format
Print the name of the top scorer.
Sample Test Cases
|
Sample Input 1
3 Sachin 100 Sehwag 80 Ganguly 60 |
Sample Output 1
Sachin |
|
Sample Input 2
2 A 100 B 90 |
Sample Output 2
A |
|
Sample Input 3
3 P 40 Q 60 R 80 |
Sample Output 3
R |
9
OOP — Banking with Interest
Hard
Write a class Account with balance and a method apply_interest(rate) that adds rate% to the balance.
Input Format
First line: initial balance. Second line: interest rate.
Output Format
Print the balance after interest rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
10000 5 |
Sample Output 1
10500.00 |
|
Sample Input 2
1000 10 |
Sample Output 2
1100.00 |
|
Sample Input 3
500 100 |
Sample Output 3
1000.00 |
10
OOP — Movie Catalog
Hard
Write a class Movie with title and rating, and a class Catalog that stores movies and a method best() that returns the movie with the highest rating.
Input Format
First line: integer N. Next N lines: title and rating.
Output Format
Print the title of the highest-rated movie.
Sample Test Cases
|
Sample Input 1
2 Inception 8.8 Titanic 7.8 |
Sample Output 1
Inception |
|
Sample Input 2
1 M 9.9 |
Sample Output 2
M |
|
Sample Input 3
2 A 5.5 B 9.5 |
Sample Output 3
B |
Competitive MCQs — Class and Objects
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score
0/ 39
Q1
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class Dog:
def bark(self):
print("Woof")
d = Dog()
d.bark()Correct!
Wrong — correct answer is .
d.bark() executes the method, printing "Woof".
Q2
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class Car:
def __init__(self, model):
self.model = model
c = Car("Tesla")
print(c.model)Correct!
Wrong — correct answer is .
The constructor stores model, accessible as c.model.
Q3
What is the output of this code?
class A:
def __init__(self):
self.x = 1
self.y = 2
a = A()
print(a.x + a.y)
class A:
def __init__(self):
self.x = 1
self.y = 2
a = A()
print(a.x + a.y)
Correct!
Wrong — correct answer is .
The constructor sets x=1 and y=2; their sum is 3.
Q4
How do you create an instance of class Student?
Correct!
Wrong — correct answer is .
Call the class name like a function: Student().
Q5
What does __init__ return?
Correct!
Wrong — correct answer is .
The constructor must return None; returning a value raises TypeError.
Q6
Which statement defines a class in Python?
Correct!
Wrong — correct answer is .
The class keyword defines a class, followed by a colon and block.
Q7
What is the output of this code?
class A:
count = 0
def __init__(self):
A.count += 1
a = A()
b = A()
print(A.count)
class A:
count = 0
def __init__(self):
A.count += 1
a = A()
b = A()
print(A.count)
Correct!
Wrong — correct answer is .
Each construction increments the class counter, reaching 2.
Q8
What does self represent inside a method?
Correct!
Wrong — correct answer is .
self refers to the particular object the method was called on.
Q9
Which attribute lookup happens first for obj.x?
Correct!
Wrong — correct answer is .
Python checks the instance first, then its class and ancestors.
Q10
What is the output of this code?
python
1
2
3
4
2
3
4
class Point:
x = 10
p = Point()
print(p.x)Correct!
Wrong — correct answer is .
p.x looks up the class attribute x, which is 10.
Q11
What is the output of this code?
class A:
def hi(self):
return "hi"
a = A()
print(hasattr(a, "hi"))
class A:
def hi(self):
return "hi"
a = A()
print(hasattr(a, "hi"))
Correct!
Wrong — correct answer is .
hasattr() returns True because the method exists on the instance/class.
Q12
Which term describes data attributes of an object?
Correct!
Wrong — correct answer is .
Values stored on an instance (via self.attr) are instance variables.
Q13
What is an attribute in Python classes?
Correct!
Wrong — correct answer is .
Attributes store state (variables) and behavior (methods) on objects.
Q14
What is the output of this code?
python
1
2
3
4
2
3
4
class A:
pass
a = A()
print(type(a))Correct!
Wrong — correct answer is .
type(a) reports the class of the object, including module: .
Q15
What is the output of this code?
class A:
def __init__(self):
self.data = []
a1 = A()
a2 = A()
a1.data.append(1)
print(a2.data)
class A:
def __init__(self):
self.data = []
a1 = A()
a2 = A()
a1.data.append(1)
print(a2.data)
Correct!
Wrong — correct answer is .
Each instance gets its own empty list, so a2.data is unaffected.
Q16
Can two objects of the same class have different attribute values?
Correct!
Wrong — correct answer is .
Each instance carries its own attributes; they are independent.
Q17
Which method is called automatically when you print an object?
Correct!
Wrong — correct answer is .
print() invokes __str__ if defined, otherwise falling back to __repr__.
Q18
Which special method returns a readable string for an object?
Correct!
Wrong — correct answer is .
__str__ defines what print(obj)/str(obj) shows.
Q19
What is the output of this code?
class A:
pass
a = A()
print(a.__dict__)
class A:
pass
a = A()
print(a.__dict__)
Correct!
Wrong — correct answer is .
An instance with no attributes has an empty __dict__.
Q20
What does __repr__ normally provide?
Correct!
Wrong — correct answer is .
__repr__ aims to be precise and useful for debugging.
Q21
What is the output of this code?
class A:
def __init__(self):
self.n = 3
def __len__(self):
return self.n
print(len(A()))
class A:
def __init__(self):
self.n = 3
def __len__(self):
return self.n
print(len(A()))
Correct!
Wrong — correct answer is .
Defining __len__ lets len() work on the object, returning 3.
Q22
Which is a class attribute?
Correct!
Wrong — correct answer is .
Class attributes are defined at class indentation level and shared.
Q23
What is the output of this code?
class A:
kind = "animal"
print(A.kind)
class A:
kind = "animal"
print(A.kind)
Correct!
Wrong — correct answer is .
Class attributes can be read directly through the class name.
Q24
What happens when you set obj.x = 5 on an instance?
Correct!
Wrong — correct answer is .
Assignment targets the instance dictionary, leaving the class attribute untouched.
Q25
What is the output of this code?
class A:
x = 1
def __init__(self):
self.x = 2
a = A()
print(A.x, a.x)
class A:
x = 1
def __init__(self):
self.x = 2
a = A()
print(A.x, a.x)
Correct!
Wrong — correct answer is .
The class keeps x=1 while the instance shadows it with x=2.
Q26
Which method is invoked when you call len(obj)?
Correct!
Wrong — correct answer is .
len() delegates to the object's __len__ method.
Q27
What is the output of this code?
class A:
def __init__(self, x):
self.x = x
print(A(5).x)
class A:
def __init__(self, x):
self.x = x
print(A(5).x)
Correct!
Wrong — correct answer is .
Creating A(5) and reading .x returns 5.
Q28
What is self?
Correct!
Wrong — correct answer is .
self is automatically bound to the calling instance.
Q29
Which of these creates two independent objects?
Correct!
Wrong — correct answer is .
Calling A() twice builds two distinct instances; assignment shares one.
Q30
What is the output of this code?
class A:
pass
print(A is A)
class A:
pass
print(A is A)
Correct!
Wrong — correct answer is .
A class object refers to itself, so the identity check is True.
Q31
What is the output of this code?
class A:
def __init__(self, name):
self.name = name
a = A("Neo")
print(a.name.upper())
class A:
def __init__(self, name):
self.name = name
a = A("Neo")
print(a.name.upper())
Correct!
Wrong — correct answer is .
a.name is "Neo", and upper() converts it to "NEO".
Q32
Which statement creates an object and calls its constructor?
Correct!
Wrong — correct answer is .
Calling the class with parentheses builds the object and runs __init__.
Q33
What is the output of this code?
class A:
version = 1
A.version = 2
print(A().version)
class A:
version = 1
A.version = 2
print(A().version)
Correct!
Wrong — correct answer is .
Updating the class attribute changes what all instances see.
Q34
What is the output of this code?
class A:
pass
A.x = 100
print(A().x)
class A:
pass
A.x = 100
print(A().x)
Correct!
Wrong — correct answer is .
Attributes can be added to a class at runtime and are visible to instances.
Q35
What does a method without self cause when called on an instance?
Correct!
Wrong — correct answer is .
Python passes the instance as the first argument, so a parameterless method gets too many args.
Q36
What is the output of this code?
class A:
def __init__(self):
self.values = [1, 2, 3]
print(sum(A().values))
class A:
def __init__(self):
self.values = [1, 2, 3]
print(sum(A().values))
Correct!
Wrong — correct answer is .
The instance stores the list; sum adds 1+2+3 = 6.
Q37
What is the output of this code?
class A:
x = 1
class B(A):
x = 2
print(A().x + B().x)
class A:
x = 1
class B(A):
x = 2
print(A().x + B().x)
Correct!
Wrong — correct answer is .
A().x is 1 and B().x is 2 (overridden), summing to 3.
Q38
What does the built-in getattr(obj, "name", default) do?
Correct!
Wrong — correct answer is .
getattr safely reads an attribute with a fallback value.
Q39
What is the output of this code?
class A:
def __init__(self):
self.x = 5
print(hasattr(A(), "x"))
class A:
def __init__(self):
self.x = 5
print(hasattr(A(), "x"))
Correct!
Wrong — correct answer is .
The instance has x, so hasattr returns True.