Practice: Constructors

« Read the chapter

Q1. Basic constructor

BeginnerCoding

Write a class `Book` whose constructor takes `title` and `pages` and stores them. Create Book("Python", 300) and print both attributes.

Goal: Write a constructor.

Q2. Default parameter

BeginnerCoding

Write a class `Pen` with constructor `(self, colour="blue")`. Create one pen without arguments and print its colour.

Goal: Use default values.

Q3. Computed attribute

IntermediateCoding

Write class `Circle` with constructor taking `r` that stores `r` and also `area` as `3 * r * r`. Print area for r=2.

Goal: Derive attributes in a constructor.

Q4. Keyword arguments

IntermediateCoding

Write a class `User` with `name`, `age=18`, `city="Delhi"`. Create User("Ana", city="Pune") and print name, age, city.

Goal: Mix defaults and keywords.

Q5. Validate the age

IntermediateCoding

Write class `Person` whose constructor raises ValueError("bad age") when age is below 0. Try Person("X", -1) in try/except and print the error message.

Goal: Validate in constructors.

Q6. Safe list default

AdvancedCoding

Write class `Team` with constructor `(self, name, members=None)` that gives each team its own list. Create two teams, add "A" to the first and print both lists.

Goal: Avoid shared mutable defaults.

Q7. Count created objects

AdvancedCoding

Write class `Ticket` with a global counter list `made = []`. In `__init__`, append `self` to `made`. Create 3 tickets and print `len(made)`.

Goal: See when the constructor runs.

Q8. Full name

BeginnerCoding

Write class `Name` with `first` and `last` in constructor and attribute `full` joined by a space. Print full for ("Ada", "Lovelace").

Goal: Combine arguments.

Q9. Constructor order

BeginnerOutput

What does this print?

Code
class A:
    def __init__(self):
        print("init")

print("start")
A()
print("end")

Goal: Know when __init__ runs.

Q10. Default argument

BeginnerOutput

What does this print?

Code
class P:
    def __init__(self, x=5):
        self.x = x

print(P().x, P(9).x)

Goal: Use defaults.

Q11. Keyword order

IntermediateOutput

What does this print?

Code
class Q:
    def __init__(self, a, b):
        self.a = a
        self.b = b

q = Q(b=1, a=2)
print(q.a, q.b)

Goal: Keyword arguments.

Q12. Shared default trap

AdvancedOutput

What does this print?

Code
class Bag:
    def __init__(self, items=[]):
        self.items = items

a = Bag()
b = Bag()
a.items.append(1)
print(b.items)

Goal: Mutable default danger.

Q13. Validation message

IntermediateOutput

What does this print?

Code
class T:
    def __init__(self, v):
        if v > 10:
            raise ValueError("too big")
        self.v = v

try:
    T(11)
except ValueError as e:
    print("caught", e)

Goal: Exceptions in constructors.

Q14. Method after init

IntermediateOutput

What does this print?

Code
class C:
    def __init__(self, n):
        self.n = n * 2

    def show(self):
        return self.n + 1

print(C(4).show())

Goal: Trace constructor and method.

Q15. Fix the missing self

BeginnerDebugging

This constructor does not store the value. Fix it. Expected output: Zoe

Code
class Pet:
    def __init__(self, name):
        name = name

p = Pet("Zoe")
print(p.name)

Goal: Store attributes on self.

Q16. Fix the return

IntermediateDebugging

This constructor raises TypeError. Fix it. Expected output: 5

Code
class N:
    def __init__(self, v):
        self.v = v
        return self.v

print(N(5).v)

Goal: Never return from __init__.

Q17. Fix the init name

BeginnerDebugging

The constructor never runs. Fix the method name. Expected output: ready

Code
class Z:
    def _init_(self):
        self.state = "ready"

print(Z().state)

Goal: Spell special methods correctly.

Q18. Why not mutable defaults

IntermediateConceptual

Explain why `def __init__(self, items=[])` is a bad idea and how to fix it.

Goal: Understand shared defaults.

Q19. Design a constructor

IntermediateApplication

A `Rectangle` needs width and height that must be positive. Describe how its constructor should behave.

Goal: Apply validation.