Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Encapsulation and Data Protection

What will be the output of this code?

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

p = Person('Alice')
print(p.name)
Ap.name
BAlice
CError: 'name' is not defined
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand property usage in code

    The name method is decorated with @property, so p.name accesses the method and returns self._name.
  2. Step 2: Check the print output

    Since p._name is set to 'Alice', printing p.name outputs 'Alice'.
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    Property access returns stored value [OK]
Quick Trick: Access property like attribute to get stored value [OK]
Common Mistakes:
  • Expecting method call syntax with parentheses
  • Confusing property name with string output
  • Thinking property causes error without setter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes