Bird
Raised Fist0

How can you modify this class to print a message every time an object is created?

hard🚀 Application Q9 of Q15
Python - Constructors and Object Initialization
How can you modify this class to print a message every time an object is created?
class Logger:
    def __init__(self):
        pass
AAdd <code>print('Object created')</code> outside the class
BAdd <code>print('Object created')</code> inside <code>__init__</code>
CAdd a separate method to print the message
DUse a class variable to store the message
Step-by-Step Solution
Solution:
  1. Step 1: Understand when __init__ runs

    __init__ runs automatically when an object is created.
  2. Step 2: Add print statement inside __init__

    Placing print('Object created') inside __init__ prints the message on each creation.
  3. Final Answer:

    Add print('Object created') inside __init__ -> Option B
  4. Quick Check:

    Print in __init__ runs on object creation = B [OK]
Quick Trick: Put code inside __init__ to run on object creation [OK]
Common Mistakes:
MISTAKES
  • Placing print outside class or method
  • Expecting separate method to run automatically
  • Using class variables for runtime messages

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes