Inheritance is a fundamental concept in object-oriented programming that allows a new class to be based on an existing class, inheriting its properties and methods. In Python, you can create a subclass that inherits the properties and methods of a parent class using the `class` statement and the `super()` function.
Here is an example of creating a subclass that inherits from a parent class in Python:
python # Define a parent class class Animal: def __init__(self, name, species): self.name = name self.species = species def speak(self): print("I am an animal.") # Define a child class that inherits from the parent class class Dog(Animal): def __init__(self, name, breed): super().__init__(name, species="Dog") self.breed = breed def speak(self): print("Woof!") # Create an object of the child class my_dog = Dog("Buddy", "Golden Retriever") # Call a method of the object print(my_dog.name) # Output: "Buddy" print(my_dog.species) # Output: "Dog" my_dog.speak() # Output: "Woof!"
In this example, a parent class called `Animal` is defined with two properties (`name` and `species`) and one method (`speak()`). A child class called `Dog` is defined that inherits from the `Animal` class and adds one property (`breed`) and overrides the `speak()` method.
An object of the `Dog` class is created with the `Dog(“Buddy”, “Golden Retriever”)` statement. The `name`, `species`, and `speak()` methods of the object are then called with the `my_dog.name`, `my_dog.species`, and `my_dog.speak()` statements, which output messages to the console.
In Python, you can also inherit from multiple classes using multiple inheritance. Here is an example:
python # Define two parent classes class A: def method_a(self): print("Method A") class B: def method_b(self): print("Method B") # Define a child class that inherits from two parent classes class C(A, B): def method_c(self): print("Method C") # Create an object of the child class my_object = C() # Call methods of the object my_object.method_a() # Output: "Method A" my_object.method_b() # Output: "Method B" my_object.method_c() # Output: "Method C"
In this example, two parent classes called `A` and `B` are defined with one method each. A child class called `C` is defined that inherits from both `A` and `B` and adds one method. An object of the `C` class is created with the `C()` statement. The `method_a()`, `method_b()`, and `method_c()` methods of the object are then called with the `my_object.method_a()`, `my_object.method_b()`, and `my_object.method_c()` statements, which output messages to the console.
Inheritance is a powerful feature of Python and is used extensively in object-oriented programming to create reusable code and organize complex systems.