Bird
Raised Fist0

Which of the following is the correct way to define a read-only property named age in a Python class?

easy📝 Syntax Q3 of Q15
Python - Encapsulation and Data Protection

Which of the following is the correct way to define a read-only property named age in a Python class?

Adef age(self): return self._age<br>@age.setter<br>def age(self, value): self._age = value
B@property<br>def age(self): return self._age
Cdef get_age(self): return self._age<br>def set_age(self, value): self._age = value
D@property<br>def age(self, value): self._age = value
Step-by-Step Solution
Solution:
  1. Step 1: Identify read-only property syntax

    A read-only property uses only the @property decorator on a method that returns the value.
  2. Step 2: Check options

    @property
    def age(self): return self._age correctly defines a read-only property. def age(self): return self._age
    @age.setter
    def age(self, value): self._age = value defines a setter, so not read-only. def get_age(self): return self._age
    def set_age(self, value): self._age = value uses old getter/setter style, not property decorator. @property
    def age(self, value): self._age = value incorrectly uses a parameter in a property getter.
  3. Final Answer:

    @property
    def age(self): return self._age
    -> Option B
  4. Quick Check:

    Read-only property = only @property getter [OK]
Quick Trick: Read-only property has only @property getter method [OK]
Common Mistakes:
MISTAKES
  • Adding a setter for read-only property
  • Using parameters in getter method
  • Using old getter/setter methods without decorators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes