Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Constructors and Object Initialization
What will be the output of this code?
class Person:
    def __init__(self, name):
        self.name = name

p = Person('Alice')
print(p.name)
AError: name not defined
Bname
CAlice
DPerson object
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute assignment in __init__

    The name parameter is assigned to self.name, storing it in the object.
  2. Step 2: Accessing the attribute

    Printing p.name outputs the stored string 'Alice'.
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Attribute access returns 'Alice' = D [OK]
Quick Trick: Attributes set in __init__ are accessed via object.attribute [OK]
Common Mistakes:
  • Expecting the parameter name instead of attribute value
  • Confusing object print with attribute print
  • Forgetting to assign parameter to self

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes