Getters & Setters

When an attribute is private, external code cannot access it directly. Instead you provide accessor (getter) and mutator (setter) methods — the IB CS terminology. Setters can validate data before storing it.

Accessor (Getter) Method

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):  # accessor
        return self.__balance

account = BankAccount(500)
print(account.get_balance())  # → 500
500

A getter simply returns the private attribute. It does not modify anything.

Mutator (Setter) Method with Validation

class BankAccount:
    def set_balance(self, amount):
        if amount >= 0:              # validation
            self.__balance = amount
        # else: silently reject — balance unchanged

account.set_balance(-100)         # rejected
print(account.get_balance())      # → 500 (unchanged)

The setter enforces a business rule: balance cannot go negative via direct assignment. This is the power of encapsulation + mutators combined.

IB Exam Terminology

  • Accessor = getter = method that reads a private attribute
  • Mutator = setter = method that writes a private attribute (with optional validation)
  • IB questions often ask you to "write an accessor for _name" — this means write a get_name method

Your Task

  1. Complete get_celsius: return self.__celsius
  2. Complete set_celsius: only assign self.__celsius = valueif value >= -273.15 (absolute zero). Otherwise do nothing.

After set_celsius(100), the getter should return 100. After set_celsius(-300), the getter should still return 100because -300 is below absolute zero.

Section 1/4Accessor (Getter) Method

Accessor (Getter) Method

A getter simply returns the private attribute. It does not modify anything.

Getters & Setters

When an attribute is private, external code cannot access it directly. Instead you provide accessor (getter) and mutator (setter) methods — the IB CS terminology. Setters can validate data before storing it.

Accessor (Getter) Method

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):  # accessor
        return self.__balance

account = BankAccount(500)
print(account.get_balance())  # → 500
500

A getter simply returns the private attribute. It does not modify anything.

Output:

Click "Check" to run your code.