CodeGym /Courses /Python SELF EN /Initialization of Hierarchy

Initialization of Hierarchy

Python SELF EN
Level 16 , Lesson 1
Available

7.1 The super() Method

Since we're diving into inheritance hierarchy, it's useful to chat about nuances of working with base class fields and methods. Python has a special super() method for this. This method is used to call base class methods inside a child class.

It has three main applications:

Calling parent class methods:

The super() method lets you call a parent class method from a child class without explicitly stating the parent class name. This is super handy when dealing with multiple inheritance and helps avoid mistakes when the class hierarchy changes.

Initializing base classes:

super() is often used in a child class constructor to call the base class constructor, letting you initialize base class attributes in the child class.

Supporting multiple inheritance:

With multiple inheritance, super() properly resolves the method call order (MRO, Method Resolution Order), making it the preferred method over explicitly calling parent class methods. We'll chat more about this a bit later.

7.2 Base Class Constructor

A base class constructor must be called explicitly. It might seem automatic, but it isn't. You always need to explicitly call base class constructors, as you often need to pass special arguments in them.

Example:


class Animal:
    def __init__(self, type, name):
        self.type = type
        self.name = name
         
        
class Dog(Animal):
    def __init__(self, name):
        super().__init__("Dog", name)  # Calling the base class constructor
        
class Cat(Animal):
    def __init__(self, name):
        super().__init__("Cat", name)  # Calling the base class constructor
        
        
# Creating a Dog object
dog = Dog("Buddy")
print(dog) 

In this example, the base class (Animal) constructor has two parameters: the type of animal and its name. The inheriting classes have only one — just the name.

It's in the constructors of the Dog and Cat classes where the decision is made on what exactly to pass to the base class constructor — the animal types "Dog" and "Cat".

So:

  • The base class constructor must be called in the constructor of the inheriting class.
  • You need to use the super() method for this.
  • You don't need to pass the self parameter separately — Python automatically inserts it when calling the method.

7.3 Using the super() Method

The super() method in Python can be used not just in constructors, but in other class methods to call parent class methods. This can be useful when you need to extend or modify the behavior of a method defined in a parent class.

Let's look at a few examples:

Calling a parent class method in a child method

In this example, the speak() method in the Dog class first calls the speak() method from the Animal class using super(), and then adds its own behavior.


class Animal:
    def speak(self):
        return "Some generic animal sound"
        

class Dog(Animal):
    def speak(self):
        parent_speech = super().speak()  # Calling the parent class method
        return f"{parent_speech} And the dog barks!"
        
dog = Dog()
print(dog.speak())  # Outputs: Some generic animal sound And the dog barks!

Calling a parent class method to check state

In this example, the check_health() method in the Dog class calls the check_health() method from the Animal class to add additional checks.


class Animal:
    def check_health(self):
        return "Animal is healthy"
        

class Dog(Animal):
    def check_health(self):
        parent_check = super().check_health()  # Calling the parent class method
        return f"{parent_check}. Dog needs a walk!"
        
dog = Dog()
print(dog.check_health())  # Outputs: Animal is healthy. Dog needs a walk!

Calling a parent class method in a method that modifies state

In this example, the withdraw() method in the SavingsAccount class first checks if the withdrawal limit is exceeded, and if not, calls the withdraw() method from the BankAccount class to perform the operation.


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

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            return f"Withdrew {amount}. New balance: {self.balance}"
        return "Insufficient funds"
        

class SavingsAccount(BankAccount):
    def withdraw(self, amount):
        if amount > 1000:
            return "Withdrawal limit exceeded"
        return super().withdraw(amount)  # Calling the parent class method
        

savings = SavingsAccount(1500)
print(savings.withdraw(500))  # Outputs: Withdrew 500. New balance: 1000
print(savings.withdraw(1500))  # Outputs: Withdrawal limit exceeded
2
Task
Python SELF EN, level 16, lesson 1
Locked
Supermachines.
Supermachines.
2
Task
Python SELF EN, level 16, lesson 1
Locked
Roaring.
Roaring.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION