Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Object-Oriented Programming Foundations
What will be the output of this code?
class Person:
    def __init__(self, name):
        self.name = name

p = Person('Anna')
print(p.name)
APerson
BAnna
Cp.name
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand __init__ method role

    The __init__ method sets the 'name' attribute of the object to the given value 'Anna'.
  2. Step 2: Check what print(p.name) outputs

    It prints the value stored in p.name, which is 'Anna'.
  3. Final Answer:

    Anna -> Option B
  4. Quick Check:

    Attribute access = 'Anna' [OK]
Quick Trick: Attributes set in __init__ are accessed by object.attribute [OK]
Common Mistakes:
MISTAKES
  • Expecting print to show variable name instead of value
  • Confusing class name with attribute
  • Forgetting to pass argument to constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes