Defining Methods in a Parent Class with Python

Defining Methods in a Parent Class

First, let’s start with a parent class that has some methods.

Example: 

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def speak(self):
        return "Animal sound"
    def age_in_human_years(self):
        return self.age * 7
  • The Animal class has a method speak() that returns a generic animal sound and another method age_in_human_years() that converts the age of the animal to human years.

Adding Methods to a Child Class

You can add methods to a child class to provide additional functionality or override existing methods.

Example: 

class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)
        self.breed = breed
    def speak(self):
        return "Woof!"
    def fetch(self):
        return f"{self.name} is fetching the ball."
    def dog_years(self):
        return self.age * 7
  • The Dog class inherits from Animal and adds a new method fetch() that is specific to dogs.
  • It also overrides the speak() method to provide a dog-specific sound.
  • The dog_years() method is similar to age_in_human_years() but demonstrates how you can define methods specific to the child class.

Using Methods from the Parent Class

You can still use methods from the parent class in the child class, including the overridden methods.

Example: 

my_dog = Dog("Rex", 5, "Labrador")
print(my_dog.speak())               # Woof!
print(my_dog.fetch())               # Rex is fetching the ball.
print(my_dog.dog_years())           # 35
print(my_dog.age_in_human_years())  # 35
  • my_dog.speak() uses the overridden method in Dog.
  • my_dog.fetch() uses the new method specific to Dog.
  • my_dog.age_in_human_years() uses the inherited method from Animal.
  1. Calling Parent Class Methods from Child Class

You can call methods from the parent class within the child class using super(), especially useful when you want to extend the functionality rather than completely override it.

Example: 

class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color
    def speak(self):
        return "Meow!"
    def describe(self):
        return f"{self.name} is a {self.age}-year-old {self.color} cat."
    def age_in_human_years(self):
        # Extend functionality to include a special message
        return f"{super().age_in_human_years()} human years (Cat's version)"
  • In the Cat class, speak() is overridden, and describe() is a new method.
  • The age_in_human_years() method is extended to include additional information while still calling the parent’s method using super().

Usage: 

my_cat = Cat("Whiskers", 3, "black")
print(my_cat.speak())               # Meow!
print(my_cat.describe())            # Whiskers is a 3-year-old black cat.
print(my_cat.age_in_human_years())  # 21 human years (Cat's version)

Combining Parent and Child Methods

Sometimes, you might want to use methods from both the parent and the child class together.

Example: 

class Bird(Animal):
    def __init__(self, name, age, species):
        super().__init__(name, age)
        self.species = species
    def speak(self):
        return "Chirp!"
    def fly(self):
        return f"{self.name} is flying."
    def age_in_human_years(self):
        # Calculate age for birds differently
        human_years = self.age * 5
        return f"{human_years} human years (Bird's version)"
  • The Bird class adds a new method fly() and provides a specific implementation for age_in_human_years().

Usage: 

my_bird = Bird("Tweety", 2, "Canary")
print(my_bird.speak())               # Chirp!
print(my_bird.fly())                 # Tweety is flying.
print(my_bird.age_in_human_years())  # 10 human years (Bird's version)

Inheritance and Method Resolution

In Python, method resolution order (MRO) determines the order in which base classes are looked up when searching for a method. You can view the MRO of a class with ClassName.__mro__.

Example: 

class A:
    def method(self):
        return "Method in A"
class B(A):
    def method(self):
        return "Method in B"
class C(A):
    def method(self):
        return "Method in C"
class D(B, C):
    pass
print(D.__mro__)  # Outputs: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
  • Here, D will use the method from class B because B is listed before C in the MRO.

Summary

  • Defining Methods: You can define methods in both parent and child classes to provide or extend functionality.
  • Overriding Methods: You can override parent class methods in the child class to change or extend behavior.
  • Calling Parent Methods: Use super() to call parent class methods from within a child class, especially useful when extending functionality.
  • Combining Methods: Combine methods from both parent and child classes to create complex behavior.
  • Method Resolution Order (MRO): Understand the MRO to predict which method will be called in complex inheritance scenarios.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *