1. LPU MCA Semester 1
  2. CAB106
  3. Unit 3

CAB106 · Unit 3: Encapsulation, inheritance and polymorphism

Getters and setters

9 practice questions

Key points

  • @property makes a method read like an attribute
  • A setter can validate before storing
  • A property without a setter is read-only
  • += calls the getter and then the setter

A getter reads a value and a setter changes it under rules. Python supports explicit methods such as get_n() and set_n(v), but the idiomatic tool is the property. A method decorated with @property is read like an attribute (obj.area, no brackets) and runs its code each time it is accessed. A setter is added with @name.setter, and it can validate or adjust a value, for example raising ValueError for a negative age.

ToolUse
@propertyRead-only computed attribute
@x.setterControlled assignment
get_x() / set_x()Explicit methods, less common in Python

A property with no setter is read-only: assigning to it raises AttributeError. A property computed from other attributes is always current, because it recalculates on every access. The data is normally stored in a private or protected attribute such as _age, so the property name and the storage name differ. A compound assignment like a.v += 1 calls the getter, then the setter.

Exam trap: a setter must store the value in a differently named attribute. Writing self.age = v inside the age setter calls the setter again and recurses forever.

Try two questions

Question 1 · Tier 3, Apply

Which design hides how a value is stored while callers still write obj.x?

  1. A property whose data is kept in a private attribute
  2. A public attribute that callers assign to directly
  3. A class variable that every object shares
  4. A static method that always returns a constant
Show the answer

A. A property keeps the obj.x syntax while the storage and rules stay hidden.

Why not B: A public attribute exposes how the value is stored.

Why not C: A shared class variable does not control access per object.

Why not D: A static method is called with brackets and has no object data.

Question 2 · Tier 2, Understand

What is the main reason to use a setter instead of a plain public attribute?

  1. It makes the attribute faster to read than a plain attribute
  2. It allows the attribute to hold more than one type of value
  3. It stops the attribute from being stored in the object at all
  4. It can validate or adjust a value before storing it
Show the answer

D. A setter is a controlled entry point where rules can be enforced.

Why not A: A setter adds a method call, so it does not speed up access.

Why not B: Python attributes can already hold any type.

Why not C: The value is still stored, only under controlled rules.