Single Inheritance in Python
- Get link
- X
- Other Apps
Single Inheritance in Python
Inheritance is one of the fundamental concepts of object-oriented programming (OOP) that allows us to define a new class based on an existing class. In Python, we can create new classes by deriving from existing classes, and single inheritance is the most basic type of inheritance in Python.
Single inheritance is a type of inheritance in which a subclass inherits from a single parent class. The subclass inherits all the attributes and methods of the parent class, and it can also add new attributes and methods of its own.
Here's an example of single inheritance in Python:
class Animal: def __init__(self, name, sound): self.name = name self.sound = sound def speak(self): print(f"{self.name} says {self.sound}.") class Dog(Animal): def __init__(self, name): super().__init__(name, "woof") dog = Dog("Buddy") dog.speak() # output: Buddy says woof.
In the example above, we have two classes: Animal
and Dog
. The Dog
class is derived from the Animal
class, which is the parent class.
The Animal
class has an __init__()
method that initializes two instance variables name
and sound
. It also has a speak()
method that prints out the name of the animal and the sound it makes.
The Dog
class has its own __init__()
method that calls the __init__()
method of the parent class using the super()
function. It sets the sound
attribute to "woof"
and passes the name
argument to the parent class's __init__()
method.
We then create an instance of the Dog
class called dog
, and call its speak()
method. The output is Buddy says woof.
, which shows that the Dog
class inherited the speak()
method from its parent class and was able to use it to print out its name and sound.
Single inheritance is a simple and straightforward way to reuse code and build more complex classes based on existing ones. It also promotes code reusability and modularity, making it easier to maintain and update code.
In conclusion, single inheritance is a powerful feature of object-oriented programming in Python that allows us to create new classes based on existing ones. It is a basic building block of OOP that promotes code reusability and modularity, and can be used to build more complex classes by inheriting attributes and methods from parent classes.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments