Bird
Raised Fist0

You want to create a class Product that stores name and price. Which constructor correctly initializes these attributes and allows creating an object with Product('Pen', 1.5)?

hard🚀 Application Q8 of Q15
Python - Constructors and Object Initialization
You want to create a class Product that stores name and price. Which constructor correctly initializes these attributes and allows creating an object with Product('Pen', 1.5)?
Adef __init__(name, price): self.name = name self.price = price
Bdef __init__(self, name, price): self.name = name self.price = price
Cdef __init__(self): self.name = name self.price = price
Ddef __init__(self, name, price): name = self.name price = self.price
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor parameters and assignments

    Constructor must accept self, name, price and assign self.name = name, self.price = price.
  2. Step 2: Validate object creation

    def __init__(self, name, price): self.name = name self.price = price matches correct syntax and allows Product('Pen', 1.5) creation.
  3. Final Answer:

    def __init__(self, name, price): self.name = name self.price = price -> Option B
  4. Quick Check:

    Correct parameter and self assignment = def __init__(self, name, price): self.name = name self.price = price [OK]
Quick Trick: Assign parameters to self attributes in constructor [OK]
Common Mistakes:
MISTAKES
  • Omitting self parameter
  • Assigning attributes backwards
  • Not accepting parameters in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes