About Lesson
Python Inheritance
Inheritance is a powerful feature of object-oriented programming that allows a class to inherit attributes and methods from another class.
1. Creating a Parent Class
You can create a parent class with attributes and methods that will be inherited by its subclasses.
Example:
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass # Placeholder method
2. Creating a Subclass
A subclass can inherit attributes and methods from its parent class using the super()
function.
Example:
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def sound(self):
return "Woof!"
3. Using Inherited Methods
Subclasses can use inherited methods from the parent class.
Example:
dog = Dog("Buddy", "Golden Retriever")
print(dog.sound()) # Output: Woof!
4. Overriding Methods
Subclasses can override methods of the parent class by defining the same method name.
Example:
class Cat(Animal):
def sound(self):
return "Meow!"
cat = Cat("Whiskers")
print(cat.sound()) # Output: Meow!
Conclusion
Inheritance allows you to create classes that are based on existing classes, enabling code reuse and the creation of a hierarchy of classes with increasing levels of specialization.
Join the conversation