Practice: Constructors
Q1. Basic constructor
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
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
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
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
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
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
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
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
What does this print?
class A:
def __init__(self):
print("init")
print("start")
A()
print("end")Goal: Know when __init__ runs.
Q10. Default argument
What does this print?
class P:
def __init__(self, x=5):
self.x = x
print(P().x, P(9).x)Goal: Use defaults.
Q11. Keyword order
What does this print?
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
What does this print?
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
What does this print?
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
What does this print?
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
This constructor does not store the value. Fix it. Expected output: Zoe
class Pet:
def __init__(self, name):
name = name
p = Pet("Zoe")
print(p.name)Goal: Store attributes on self.
Q16. Fix the return
This constructor raises TypeError. Fix it. Expected output: 5
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
The constructor never runs. Fix the method name. Expected output: ready
class Z:
def _init_(self):
self.state = "ready"
print(Z().state)Goal: Spell special methods correctly.
Q18. Why not mutable defaults
Explain why `def __init__(self, items=[])` is a bad idea and how to fix it.
Goal: Understand shared defaults.
Q19. Design a constructor
A `Rectangle` needs width and height that must be positive. Describe how its constructor should behave.
Goal: Apply validation.