Bird
0
0

You want to create a class Book that stores title and author. Which code correctly creates an object and prints the title and author?

hard📝 Application Q15 of 15
Python - Classes and Object Lifecycle
You want to create a class Book that stores title and author. Which code correctly creates an object and prints the title and author?
Aclass Book: def __init__(self): self.title = '1984' self.author = 'Orwell' b = Book('1984', 'Orwell') print(b.title, b.author)
Bclass Book: def __init__(self, title, author): title = title author = author b = Book('1984', 'Orwell') print(b.title, b.author)
Cclass Book: def __init__(self, title, author): self.title = title b = Book('1984', 'Orwell') print(b.title, b.author)
Dclass Book: def __init__(self, title, author): self.title = title self.author = author b = Book('1984', 'Orwell') print(b.title, b.author)
Step-by-Step Solution
Solution:
  1. Step 1: Check attribute assignment in constructor

    The correct code defines __init__ with title and author parameters and assigns self.title = title and self.author = author.
  2. Step 2: Verify object creation and printing

    The object is created by passing arguments Book('1984', 'Orwell') matching the parameters, and both attributes print correctly. Others fail on missing self, incomplete assignments, or parameter mismatch.
  3. Final Answer:

    Correctly assigns both attributes to self using parameters -> Option D
  4. Quick Check:

    Assign all attributes with self and pass parameters [OK]
Quick Trick: Assign all attributes with self and pass parameters [OK]
Common Mistakes:
  • Not assigning attributes to self
  • Missing parameters in constructor
  • Providing arguments to a parameterless constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes