super() and Protected Members

When a child class has its own __init__, it must explicitly call the parent's constructor using super().__init__(). Without this, the parent's instance variables are never set up.

Calling the Parent Constructor

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age  = age
class Customer(Person):
    def __init__(self, name, age, customer_id):
        super().__init__(name, age)   # run Person.__init__ first
        self._customer_id = customer_id
  • super() returns a reference to the parent class
  • Always call super().__init__() as the first line of the child's __init__
  • In Java the equivalent is super(name, age);

Protected Members in Inheritance

Protected attributes (_name) are accessible from within the child class. Private attributes (__name) are not directly accessible in child classes.

class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self._salary = salary
    def get_info(self):
        # Can access self._name because it is protected
        return f"{self._name} earns £{self._salary}"

The IB Person-Customer Hierarchy

The IB CS curriculum uses a Person → Customer / Employee hierarchy as its main example. Common attributes (name, phone, email) live in Person. Specialised attributes (loyalty points for Customer; salary for Employee) live in the child class.

┌─────────────────────┐
│       Person        │
├─────────────────────┤
│ # _name             │
│ # _age              │
├─────────────────────┤
│ + get_info()        │
└────────┬────────────┘
         ↓ (inherits)
┌─────────────────────┐
│      Customer       │
├─────────────────────┤
│ # _customer_id      │
└─────────────────────┘

Your Task

  1. Write class Customer(Person):
  2. In __init__(self, name, age, customer_id), call super().__init__(name, age) first
  3. Then store self._customer_id = customer_id

After your changes, c.get_info() (inherited from Person) should return "Alice, age 30" without any changes to the Person class.

Section 1/4Calling the Parent Constructor

Calling the Parent Constructor

Explore this concept

super() and Protected Members

When a child class has its own __init__, it must explicitly call the parent's constructor using super().__init__(). Without this, the parent's instance variables are never set up.

Calling the Parent Constructor

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age  = age
class Customer(Person):
    def __init__(self, name, age, customer_id):
        super().__init__(name, age)   # run Person.__init__ first
        self._customer_id = customer_id
  • super() returns a reference to the parent class
  • Always call super().__init__() as the first line of the child's __init__
  • In Java the equivalent is super(name, age);

Output:

Click "Check" to run your code.