Bird
0
0

You want to create a class Book that stores title and author. Which is the best way to define the __init__ method to set these attributes?

hard📝 Application Q15 of 15
Python - Classes and Object Lifecycle
You want to create a class Book that stores title and author. Which is the best way to define the __init__ method to set these attributes?
Adef __init__(self, title, author): self.title = title self.author = author
Bdef __init__(title, author): self.title = title self.author = author
Cdef __init__(self): title = None author = None
Ddef __init__(self, title, author): title = self.title author = self.author
Step-by-Step Solution
Solution:
  1. Step 1: Define __init__ with self and parameters

    The method must have self as first parameter, then title and author to receive values.
  2. Step 2: Assign parameters to object attributes

    Use self.title = title and self.author = author to store values in the object.
  3. Final Answer:

    def __init__(self, title, author): self.title = title self.author = author -> Option A
  4. Quick Check:

    Init method sets attributes using self [OK]
Quick Trick: Use self.param = param to store values in __init__ [OK]
Common Mistakes:
  • Omitting self parameter
  • Assigning attributes backwards
  • Not passing parameters to __init__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes