Constructors Practice
Use __init__, default and parameterized constructors to initialise objects.
1
Default Constructor — No Arguments
Easy
Write a class Demo with a constructor that prints 'Object created'. Create an object.
Input Format
No input.
Output Format
Print 'Object created'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Object created |
|
Sample Input 2
|
Sample Output 2
Object created |
|
Sample Input 3
|
Sample Output 3
Object created |
2
Constructor with One Parameter
Easy
Write a class Person with a constructor that takes name and stores it. Read a name, create an object, and print it.
Input Format
A single line containing a name.
Output Format
Print the name.
Sample Test Cases
|
Sample Input 1
Alice |
Sample Output 1
Alice |
|
Sample Input 2
Bob |
Sample Output 2
Bob |
|
Sample Input 3
Sam |
Sample Output 3
Sam |
3
Constructor with Two Parameters
Easy
Write a class Rectangle with a constructor that takes length and breadth and stores them.
Input Format
A single line containing two space-separated integers.
Output Format
Print the length and breadth on separate lines.
Sample Test Cases
|
Sample Input 1
4 6 |
Sample Output 1
4 6 |
|
Sample Input 2
7 8 |
Sample Output 2
7 8 |
|
Sample Input 3
1 1 |
Sample Output 3
1 1 |
4
Constructor Initializes Attributes
Easy
Write a class Car with a constructor that takes brand and model. Read both, create an object, and print them.
Input Format
First line: brand. Second line: model.
Output Format
Print 'Brand: [brand]' and 'Model: [model]' on separate lines.
Sample Test Cases
|
Sample Input 1
Toyota Camry |
Sample Output 1
Brand: Toyota Model: Camry |
|
Sample Input 2
Honda City |
Sample Output 2
Brand: Honda Model: City |
|
Sample Input 3
Ford Figo |
Sample Output 3
Brand: Ford Model: Figo |
5
Constructor with Default Value
Easy
Write a class Student with a constructor that takes name and age=18 by default. Read a name, create an object, and print name and age.
Input Format
A single line containing a name.
Output Format
Print 'Name: [name]' and 'Age: [age]'.
Sample Test Cases
|
Sample Input 1
Alice |
Sample Output 1
Name: Alice Age: 18 |
|
Sample Input 2
Bob |
Sample Output 2
Name: Bob Age: 18 |
|
Sample Input 3
Sam |
Sample Output 3
Name: Sam Age: 18 |
6
Constructor Stores Radius
Easy
Write a class Circle with a constructor that takes radius and stores it.
Input Format
A single line containing the radius.
Output Format
Print the radius.
Sample Test Cases
|
Sample Input 1
7 |
Sample Output 1
7 |
|
Sample Input 2
3 |
Sample Output 2
3 |
|
Sample Input 3
0 |
Sample Output 3
0 |
7
Constructor with Print
Easy
Write a class Greeting with a constructor that prints 'Hello, [name]!' using the name argument.
Input Format
A single line containing a name.
Output Format
Print the greeting.
Sample Test Cases
|
Sample Input 1
Bob |
Sample Output 1
Hello, Bob! |
|
Sample Input 2
Alice |
Sample Output 2
Hello, Alice! |
|
Sample Input 3
Sam |
Sample Output 3
Hello, Sam! |
8
Multiple Objects from Constructor
Easy
Write a class Point with a constructor taking x and y. Create 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) |
9
Constructor with Keyword Arguments
Easy
Write a class Product with a constructor that takes name and price as keyword arguments.
Input Format
First line: name. Second line: price.
Output Format
Print 'Name: [name]' and 'Price: [price]'.
Sample Test Cases
|
Sample Input 1
Laptop 50000 |
Sample Output 1
Name: Laptop Price: 50000 |
|
Sample Input 2
Phone 20000 |
Sample Output 2
Name: Phone Price: 20000 |
|
Sample Input 3
TV 10000 |
Sample Output 3
Name: TV Price: 10000 |
10
Constructor Sets a Fixed Value
Easy
Write a class Planet with a constructor that always sets attribute kind = 'planet'. Create an object and print kind.
Input Format
No input.
Output Format
Print 'planet'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
planet |
|
Sample Input 2
|
Sample Output 2
planet |
|
Sample Input 3
|
Sample Output 3
planet |
1
Constructor Calls a Method
Medium
Write a class Circle with a constructor that takes radius and calls a method show() that prints the radius.
Input Format
A single line containing the radius.
Output Format
Print the radius.
Sample Test Cases
|
Sample Input 1
5 |
Sample Output 1
5 |
|
Sample Input 2
9 |
Sample Output 2
9 |
|
Sample Input 3
2 |
Sample Output 3
2 |
2
Constructor with List Parameter
Medium
Write a class Cart with a constructor that takes a list of items and stores it.
Input Format
First line: integer N. Second line: N space-separated item names.
Output Format
Print the list of items.
Sample Test Cases
|
Sample Input 1
3 apple mango banana |
Sample Output 1
['apple', 'mango', 'banana'] |
|
Sample Input 2
2 x y |
Sample Output 2
['x', 'y'] |
|
Sample Input 3
1 z |
Sample Output 3
['z'] |
3
Constructor Overloading Simulation
Medium
Write a class Area with a constructor that accepts either 1 argument (square side) or 2 arguments (length and breadth) and prints the area accordingly.
Input Format
A single line containing 1 or 2 space-separated integers.
Output Format
Print the computed area.
Sample Test Cases
|
Sample Input 1
5 |
Sample Output 1
25 |
|
Sample Input 2
4 5 |
Sample Output 2
20 |
|
Sample Input 3
6 |
Sample Output 3
36 |
4
Default + Custom Constructor Combo
Medium
Write a class Employee with __init__(name, salary=30000). Create objects with and without salary and print both.
Input Format
First line: name with salary. Second line: name only.
Output Format
Print each employee's name and salary on separate lines.
Sample Test Cases
|
Sample Input 1
Alice 50000 Bob |
Sample Output 1
Alice 50000 Bob 30000 |
|
Sample Input 2
A 40000 B |
Sample Output 2
A 40000 B 30000 |
|
Sample Input 3
C 100000 D |
Sample Output 3
C 100000 D 30000 |
5
Constructor Validates Input
Medium
Write a class Temperature with a constructor that takes celsius and prints an error 'Invalid temperature' if it is below -273.15, else stores it.
Input Format
A single line containing the celsius value.
Output Format
Print the temperature, or the error message.
Sample Test Cases
|
Sample Input 1
-300 |
Sample Output 1
Invalid temperature |
|
Sample Input 2
100 |
Sample Output 2
100 |
|
Sample Input 3
-274 |
Sample Output 3
Invalid temperature |
6
Copy Constructor Simulation
Medium
Write a class Book with title attribute and a method copy() that returns a new Book object with the same title.
Input Format
A single line containing a book title.
Output Format
Print the title of the copy.
Sample Test Cases
|
Sample Input 1
Python |
Sample Output 1
Python |
|
Sample Input 2
Java |
Sample Output 2
Java |
|
Sample Input 3
C |
Sample Output 3
C |
7
Constructor with Calculation
Medium
Write a class Rectangle with a constructor that takes length and breadth and immediately computes and stores area.
Input Format
A single line containing two space-separated integers.
Output Format
Print the stored area.
Sample Test Cases
|
Sample Input 1
3 7 |
Sample Output 1
21 |
|
Sample Input 2
5 5 |
Sample Output 2
25 |
|
Sample Input 3
1 9 |
Sample Output 3
9 |
8
Constructor and Method Interaction
Medium
Write a class BankAccount with a constructor taking balance and a method deposit(amount) that adds to it.
Input Format
First line: initial balance. Second line: deposit amount.
Output Format
Print the final balance.
Sample Test Cases
|
Sample Input 1
1000 250 |
Sample Output 1
1250 |
|
Sample Input 2
0 100 |
Sample Output 2
100 |
|
Sample Input 3
50 50 |
Sample Output 3
100 |
9
Class with No __init__
Medium
Write a class Point without __init__ where attributes are set directly after object creation. Read x and y, set them, and print.
Input Format
A single line containing two space-separated integers.
Output Format
Print the point as (x, y).
Sample Test Cases
|
Sample Input 1
2 3 |
Sample Output 1
(2, 3) |
|
Sample Input 2
4 5 |
Sample Output 2
(4, 5) |
|
Sample Input 3
-1 0 |
Sample Output 3
(-1, 0) |
10
Constructor with Type Conversion
Medium
Write a class Number with a constructor that takes a string and converts it to an integer before storing.
Input Format
A single line containing a numeric string.
Output Format
Print the integer value.
Sample Test Cases
|
Sample Input 1
1234 |
Sample Output 1
1234 |
|
Sample Input 2
999 |
Sample Output 2
999 |
|
Sample Input 3
-7 |
Sample Output 3
-7 |
1
Banking System with Constructors
Hard
Write a class Account with a constructor taking account number and initial balance, plus deposit() and withdraw() methods.
Input Format
First line: account number. Second line: initial balance. Third line: deposit. Fourth line: withdrawal.
Output Format
Print balance after deposit, then after withdrawal.
Sample Test Cases
|
Sample Input 1
A1001 5000 2000 1500 |
Sample Output 1
7000 5500 |
|
Sample Input 2
A1 1000 500 200 |
Sample Output 2
1500 1300 |
|
Sample Input 3
B2 0 0 0 |
Sample Output 3
0 0 |
2
Constructor Chains via Inheritance
Hard
Write a parent class Animal with a constructor taking name, and a child class Dog that calls the parent constructor with super() and adds a breed.
Input Format
First line: name. Second line: breed.
Output Format
Print 'Name: [name]' and 'Breed: [breed]'.
Sample Test Cases
|
Sample Input 1
Rocky Labrador |
Sample Output 1
Name: Rocky Breed: Labrador |
|
Sample Input 2
Max Pug |
Sample Output 2
Name: Max Breed: Pug |
|
Sample Input 3
Bella Beagle |
Sample Output 3
Name: Bella Breed: Beagle |
3
Student Record with Constructor
Hard
Write a class Student with a constructor taking name and marks list, and a method average() that returns the average.
Input Format
First line: name. Second line: three space-separated marks.
Output Format
Print 'Average: [avg]' rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
Alice 80 90 70 |
Sample Output 1
Average: 80.00 |
|
Sample Input 2
Bob 50 60 70 |
Sample Output 2
Average: 60.00 |
|
Sample Input 3
Sam 100 100 100 |
Sample Output 3
Average: 100.00 |
4
Library Book with Constructor
Hard
Write a class Book with a constructor taking title, author, and copies. Add a method borrow() that decreases copies and prints 'Borrowed' or 'Not available'.
Input Format
First line: title, author, copies space-separated. Second line: number of borrows.
Output Format
Print the result of each borrow, then the remaining copies.
Sample Test Cases
|
Sample Input 1
Python Guido 3 2 |
Sample Output 1
Borrowed Borrowed Remaining: 1 |
|
Sample Input 2
C Guido 1 1 |
Sample Output 2
Borrowed Remaining: 0 |
|
Sample Input 3
D Kern 0 1 |
Sample Output 3
Not available Remaining: 0 |
5
Constructor with *args
Hard
Write a class ShoppingCart with a constructor that takes *args as initial items and stores them in a list.
Input Format
A single line containing N space-separated items.
Output Format
Print the list of items.
Sample Test Cases
|
Sample Input 1
apple mango banana grapes |
Sample Output 1
['apple', 'mango', 'banana', 'grapes'] |
|
Sample Input 2
a b |
Sample Output 2
['a', 'b'] |
|
Sample Input 3
x |
Sample Output 3
['x'] |
6
OOP — Employee with ID Counter
Hard
Write a class Employee whose constructor auto-assigns an incrementing employee ID starting from 1, and takes a name. Create 3 employees and print their IDs and names.
Input Format
Three lines, each containing a name.
Output Format
Print 'ID: [id], Name: [name]' for each.
Sample Test Cases
|
Sample Input 1
Alice Bob Carol |
Sample Output 1
ID: 1, Name: Alice ID: 2, Name: Bob ID: 3, Name: Carol |
|
Sample Input 2
A B C |
Sample Output 2
ID: 1, Name: A ID: 2, Name: B ID: 3, Name: C |
|
Sample Input 3
X Y Z |
Sample Output 3
ID: 1, Name: X ID: 2, Name: Y ID: 3, Name: Z |
7
Constructor with Dictionary
Hard
Write a class Config with a constructor taking a dictionary of settings and a method get(key) that returns the value or 'Not found'.
Input Format
First line: N. Next N lines: key value. Last line: key to fetch.
Output Format
Print the value, or 'Not found'.
Sample Test Cases
|
Sample Input 1
2 host localhost port 3306 host |
Sample Output 1
localhost |
|
Sample Input 2
1 k v k |
Sample Output 2
v |
|
Sample Input 3
2 a 1 b 2 c |
Sample Output 3
Not found |
8
Vehicle Hierarchy Constructors
Hard
Write a class Vehicle with a constructor taking brand, and a class Car extending it with a constructor adding model.
Input Format
First line: brand. Second line: model.
Output Format
Print 'Brand: [brand]' and 'Model: [model]'.
Sample Test Cases
|
Sample Input 1
Honda Civic |
Sample Output 1
Brand: Honda Model: Civic |
|
Sample Input 2
Suzuki Swift |
Sample Output 2
Brand: Suzuki Model: Swift |
|
Sample Input 3
Kia Seltos |
Sample Output 3
Brand: Kia Model: Seltos |
9
OOP — Queue with Constructor
Hard
Write a class Queue with a constructor taking an initial list, and methods enqueue(x) and dequeue() that remove from the front.
Input Format
First line: initial elements space-separated. Second line: element to enqueue.
Output Format
Print the queue after enqueue and after dequeue.
Sample Test Cases
|
Sample Input 1
1 2 3 4 |
Sample Output 1
[2, 3, 4] |
|
Sample Input 2
1 2 3 4 |
Sample Output 2
[2, 3, 4] |
|
Sample Input 3
5 6 7 |
Sample Output 3
[6, 7] |
10
Constructor with Exception Handling
Hard
Write a class Account with a constructor that raises ValueError 'Negative balance' if the initial balance is negative.
Input Format
A single line containing the initial balance.
Output Format
Print the balance, or 'Negative balance' for invalid input.
Sample Test Cases
|
Sample Input 1
-50 |
Sample Output 1
Negative balance |
|
Sample Input 2
100 |
Sample Output 2
100 |
|
Sample Input 3
-1 |
Sample Output 3
Negative balance |
Competitive MCQs — Constructors
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score
0/ 39
Q1
What is the name of the constructor method in Python?
Correct!
Wrong — correct answer is .
The constructor is __init__ (called when an instance is made).
Q2
When is the constructor called?
Correct!
Wrong — correct answer is .
Python calls __init__ automatically after the instance is created.
Q3
What is the output of this code?
class A:
def __init__(self, a, b):
self.s = a + b
print(A(2, 3).s)
class A:
def __init__(self, a, b):
self.s = a + b
print(A(2, 3).s)
Correct!
Wrong — correct answer is .
The constructor sums 2 and 3 into self.s.
Q4
What is the output of this code?
python
1
2
3
4
2
3
4
class A:
def __init__(self):
print("Created")
obj = A()Correct!
Wrong — correct answer is .
Creating A() triggers __init__, printing "Created".
Q5
Can __init__ accept keyword arguments?
Correct!
Wrong — correct answer is .
Constructors are ordinary methods, so keyword arguments are allowed.
Q6
Can a class have more than one __init__ method?
Correct!
Wrong — correct answer is .
Python does not support constructor overloading; redefine __init__ once.
Q7
What is the output of this code?
class A:
def __init__(self):
print("init")
A()
class A:
def __init__(self):
print("init")
A()
Correct!
Wrong — correct answer is .
Instantiating the class runs __init__, printing "init".
Q8
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class A:
def __init__(self, x=5):
self.x = x
a = A()
print(a.x)Correct!
Wrong — correct answer is .
The default x=5 is used when no argument is passed.
Q9
Which operator is used to create an object?
Correct!
Wrong — correct answer is .
ClassName(...) invokes the constructor without a new keyword.
Q10
What is the purpose of a constructor with parameters?
Correct!
Wrong — correct answer is .
Parameters let different instances start with different data.
Q11
What is the output of this code?
class A:
def __init__(self, items=None):
self.items = items if items is not None else []
a = A()
a.items.append(1)
print(A().items)
class A:
def __init__(self, items=None):
self.items = items if items is not None else []
a = A()
a.items.append(1)
print(A().items)
Correct!
Wrong — correct answer is .
The default None guard gives each instance its own new list.
Q12
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class A:
def __init__(self, n):
self.n = n * 2
a = A(4)
print(a.n)Correct!
Wrong — correct answer is .
The constructor stores n * 2 = 8 in self.n.
Q13
Why is using a mutable default like def __init__(self, items=[]) risky?
Correct!
Wrong — correct answer is .
Mutable defaults persist on the function, so instances share the same list.
Q14
Which special method is called before __init__ to create the instance?
Correct!
Wrong — correct answer is .
__new__ allocates the instance; __init__ then initializes it.
Q15
What is the output of this code?
class A:
def __init__(self, x=1, y=2):
self.x = x
self.y = y
a = A(5)
print(a.x + a.y)
class A:
def __init__(self, x=1, y=2):
self.x = x
self.y = y
a = A(5)
print(a.x + a.y)
Correct!
Wrong — correct answer is .
x is 5 while y defaults to 2, giving 5 + 2 = 7.
Q16
What happens if __init__ has parameters but you create A() with none?
Correct!
Wrong — correct answer is .
If __init__ requires parameters, calling without them raises TypeError.
Q17
Which of these calls matches def __init__(self, name, age)?
Correct!
Wrong — correct answer is .
The call must supply both name and age in order (or by keyword).
Q18
How do you pass a value to a constructor?
Correct!
Wrong — correct answer is .
Arguments go inside the class call: A(10) → __init__(self, 10).
Q19
What is the output of this code?
class A:
def __init__(self, *vals):
self.total = sum(vals)
a = A(1, 2, 3)
print(a.total)
class A:
def __init__(self, *vals):
self.total = sum(vals)
a = A(1, 2, 3)
print(a.total)
Correct!
Wrong — correct answer is .
*vals collects 1, 2, 3 and sum gives 6.
Q20
What happens if __init__ is missing?
Correct!
Wrong — correct answer is .
If no constructor is defined, a default no-arg __init__ is inherited from object.
Q21
What is the output of this code?
class A:
def __init__(self, v=0):
self.v = v
a = A(10)
print(a.v)
class A:
def __init__(self, v=0):
self.v = v
a = A(10)
print(a.v)
Correct!
Wrong — correct answer is .
Passing 10 overrides the default, so self.v is 10.
Q22
Which of these is TRUE about __init__ overloading?
Correct!
Wrong — correct answer is .
Python uses a single __init__; simulate defaults instead.
Q23
What is the output of this code?
class A:
def __init__(self):
self.lst = []
a = A()
a.lst.append(3)
print(a.lst)
class A:
def __init__(self):
self.lst = []
a = A()
a.lst.append(3)
print(a.lst)
Correct!
Wrong — correct answer is .
a.lst is its own list, so appending 3 shows [3].
Q24
What is a constructor called during?
Correct!
Wrong — correct answer is .
Constructors run at creation time to set initial state.
Q25
What is the output of this code?
class A:
def __init__(self, name="Guest"):
self.name = name
print(A().name)
class A:
def __init__(self, name="Guest"):
self.name = name
print(A().name)
Correct!
Wrong — correct answer is .
Omitting the argument uses the default "Guest".
Q26
How does __init__ store instance data?
Correct!
Wrong — correct answer is .
self.attr = value attaches the value to the new instance.
Q27
What is the output of this code?
class A:
def __init__(self, x):
self.x = x
def get(self):
return self.x
a = A(8)
print(a.get())
class A:
def __init__(self, x):
self.x = x
def get(self):
return self.x
a = A(8)
print(a.get())
Correct!
Wrong — correct answer is .
get() reads the stored x value, 8.
Q28
Which error appears when calling A() but __init__ requires 2 args?
Correct!
Wrong — correct answer is .
Missing required arguments raise TypeError at the call site.
Q29
What is the output of this code?
class A:
def __init__(self):
self.x = self.y = 0
a = A()
print(a.x, a.y)
class A:
def __init__(self):
self.x = self.y = 0
a = A()
print(a.x, a.y)
Correct!
Wrong — correct answer is .
Chained assignment initializes both attributes to 0.
Q30
What is the output of this code?
class A:
def __init__(self, n):
self.n = n
print(A("hi").n)
class A:
def __init__(self, n):
self.n = n
print(A("hi").n)
Correct!
Wrong — correct answer is .
The constructor stores whatever value is passed, including strings.
Q31
What is the output of this code?
class A:
def __init__(self):
print("init called")
A()
A()
class A:
def __init__(self):
print("init called")
A()
A()
Correct!
Wrong — correct answer is .
Each instantiation runs __init__, so the message prints twice.
Q32
What happens if a subclass defines __init__ without calling super().__init__()?
Correct!
Wrong — correct answer is .
Python calls the child __init__ only; the parent needs an explicit super() call.
Q33
What is the output of this code?
class A:
def __init__(self, x=5):
self.x = x
a = A(5)
b = A()
print(a.x, b.x)
class A:
def __init__(self, x=5):
self.x = x
a = A(5)
b = A()
print(a.x, b.x)
Correct!
Wrong — correct answer is .
Both calls give x the value 5 — one passed, one default.
Q34
Which of these is a keyword argument when creating A?
Correct!
Wrong — correct answer is .
A(x=10) names the parameter explicitly as a keyword argument.
Q35
What is the output of this code?
class A:
def __init__(self, vals):
self.total = sum(vals)
print(A([1, 2, 3]).total)
class A:
def __init__(self, vals):
self.total = sum(vals)
print(A([1, 2, 3]).total)
Correct!
Wrong — correct answer is .
sum of the passed list is 6, stored as total.
Q36
What is the output of this code?
class A:
def __init__(self):
self.x = 1
self.y = 2
obj = A()
print(obj.__dict__)
class A:
def __init__(self):
self.x = 1
self.y = 2
obj = A()
print(obj.__dict__)
Correct!
Wrong — correct answer is .
The instance dictionary holds both attributes set by __init__.
Q37
Which method would a class use to clean up before deletion?
Correct!
Wrong — correct answer is .
The destructor __del__ is invoked when the object is garbage collected.
Q38
What is the output of this code?
class A:
def __init__(self, *args):
self.count = len(args)
print(A(1, 2, 3, 4).count)
class A:
def __init__(self, *args):
self.count = len(args)
print(A(1, 2, 3, 4).count)
Correct!
Wrong — correct answer is .
*args collects all four arguments, so count is 4.
Q39
What is the output of this code?
class A:
def __init__(self):
self.created = True
print(A().created)
class A:
def __init__(self):
self.created = True
print(A().created)
Correct!
Wrong — correct answer is .
The constructor sets created to True on the instance.