Inheritance of Class Attributes and Methods
Inheritance
is a feature where one class inherits the attributes and methods of another class.
This allows reusing and extending existing code, thereby enhancing programming efficiency.
In Python, inheritance is implemented by specifying the parent class inside parentheses when defining a new class.
class ChildClass(ParentClass):
# Contents of the child class
In the code above, ChildClass
inherits from ParentClass
.
ChildClass
can use the attributes and methods of ParentClass
.
The ParentClass is also known as the Superclass
or Base class
.
The ChildClass is also referred to as the Subclass
or Derived class
.
Why Use Inheritance?
Inheritance in object-oriented programming serves the following purposes:
-
Code Reusability
: It reduces redundancy by utilizing the code of existing classes. -
Scalability
: It allows adding new functionalities or changing existing functionalities without modifying the existing classes. -
Hierarchical Structure
: It forms a hierarchy among classes, making the program structure clearer.
Below is an example of defining a Dog
class that inherits from the Animal
class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# Example of using the class
my_dog = Dog("Buddy")
print(my_dog.speak())
# Outputs: 'Buddy barks.'
In this example, the Dog
class inherits both the name
attribute and the speak
method from the Animal
class.
It then overrides the speak
method to reflect the characteristics of a dog.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.