Introduction
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (child or derived class) to inherit properties and behaviors from another class (parent or base class). It promotes code reusability and helps in creating a hierarchy of classes with a shared set of attributes and methods.
Syntax for creating a derived class:
pythonclass BaseClass:
# Base class attributes and methods
class DerivedClass(BaseClass):
# Derived class attributes and methods
Explanation
- The
BaseClass
is the parent class that contains common attributes and methods. - The
DerivedClass
is the child class that inherits attributes and methods from theBaseClass
.
Example:
pythonclass Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self, sound):
return f"{self.name} makes a {sound} sound."
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, species="Dog")
self.breed = breed
def make_sound(self, sound="bark"):
return f"{self.name} barks: {sound}!"
# Creating objects of the derived class
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "German Shepherd")
# Accessing inherited method from the base class
print(dog1.make_sound()) # Output: Buddy barks: bark!
# Accessing attributes from the base class
print(dog2.species) # Output: Dog
In the example, the Dog
class inherits the attributes and methods from the Animal
class using the Animal
class as its base class. The Dog
class also overrides the make_sound
method to provide a custom implementation specific to dogs.
Keep in mind that this is just a brief overview of inheritance in Python. Inheritance can be multi-level, where a class can inherit from another derived class, forming a chain of inheritance. Additionally, Python supports multiple inheritance, where a class can inherit from multiple base classes. However, it's essential to use inheritance judiciously to maintain a clear and understandable class hierarchy.
0 Comments