w3resource

How to create a subclass (derived class) from a superclass (base class) in Python?

Subclass (derived class) from a superclass (base class) in Python

In Python, we can create a subclass (derived class) from a superclass (base class) by using the following syntax:

class:SubclassName(BaseClassName):. 

This syntax indicates that the "SubclassName" is inherited from the "BaseClassName", making it a subclass of the superclass.

Here's the general syntax for creating a subclass:

class BaseClassName:
    # Define attributes and methods for the superclass
class SubClassName(BaseClassName):
    # Define additional attributes and methods for the subclass

Example:

# Base class (superclass)
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        return "Unknown sound"

# Subclass
class Lion(Animal):
    def __init__(self, name, breed):
        # Call the constructor of the superclass to initialize name and species
        super().__init__(name, species="Lion")
        self.breed = breed

    def make_sound(self):
        return "Roar!"

# Create instances of the subclasses
animal_instance = Animal("Generic", "Panthera leo")
lion_instance = Lion("King", "Congo Lion")

# Call methods of the superclass and subclass
print(animal_instance.make_sound())  # Output: Unknown sound
print(lion_instance.make_sound())     # Output: Roar!
print(lion_instance.name)             # Output: King
print(lion_instance.species)          # Output: Lion
print(lion_instance.breed)            # Output: Congo Lion

In this example, we have a superclass "Animal" with attributes 'name' and 'species' and a method 'make_sound'. The subclass 'Lion' inherits from the "Animal" class and adds an additional attribute 'breed' and overrides the 'make_sound' method.

To create an instance of the subclass 'Lion', we call its constructor, which automatically calls the constructor of the superclass Animal using super().__init__(name, species="Lion"). This way, the attributes 'name' and 'species' from the superclass are initialized for the subclass. We can also add the 'breed' attribute specific to the "Lion" class.

When we call the 'make_sound()' method on the 'lion_instance', it uses the method from the subclass (Roar!) instead of the method from the superclass (Unknown sound). This shows how the subclass inherits and overrides methods from the superclass.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/how-to-create-a-subclass-derived-class-from-a-superclass-base-class-in-python.php