Bird
Raised Fist0

Consider this class:

hard🚀 Application Q15 of Q15
Python - Constructors and Object Initialization

Consider this class:

class Book:
    def __init__(self, title, author="Unknown"):
        self.title = title
        self.author = author

b1 = Book("Python 101")
b2 = Book("Learn AI", "Dr. Smith")
print(b1.author, b2.author)

What will be printed?

ADr. Smith Unknown
BPython 101 Learn AI
CUnknown Dr. Smith
DError due to missing author argument
Step-by-Step Solution
Solution:
  1. Step 1: Understand default parameter in __init__

    The author parameter has a default value "Unknown", so it is optional when creating an object.
  2. Step 2: Analyze object creations

    b1 is created with only title, so author is "Unknown". b2 provides both title and author "Dr. Smith".
  3. Step 3: Check print output

    Printing b1.author and b2.author prints "Unknown Dr. Smith".
  4. Final Answer:

    Unknown Dr. Smith -> Option C
  5. Quick Check:

    Default parameters fill missing values = A [OK]
Quick Trick: Default values fill missing arguments in __init__ [OK]
Common Mistakes:
MISTAKES
  • Expecting error when argument is missing
  • Mixing up title and author values
  • Assuming both arguments are always required

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes