Python tutorials > Object-Oriented Programming (OOP) > Classes and Objects > What is inheritance?
What is inheritance?
Basic Inheritance Example
Animal
class is the base class. The Dog
and Cat
classes are subclasses that inherit from Animal
. They inherit the __init__
method (and thus the name
attribute) and override the speak
method to provide their specific sounds. The Dog
and Cat
classes inherit the attribute and method.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.name)
dog.speak()
print(cat.name)
cat.speak()
Concepts Behind the Snippet
Animal
in the example).Dog
and Cat
).speak
method).
Real-Life Use Case
Widget
that defines common properties like position, size, and color. Then, you could create subclasses like Button
, TextField
, and Label
that inherit from Widget
and add their own specific properties and behaviors. This avoids duplicating code related to the basic widget properties in each subclass. Another example is in game development, where you could have a base class Character
and then subclasses like Player
, Enemy
, NPC
inheriting common attributes like health, position, and animation methods but providing unique behaviors.
Best Practices
abc
module) to define interfaces and ensure that subclasses implement required methods.
Interview Tip
When to Use Inheritance
Dog
is an Animal
. Inheritance is appropriate when the subclass needs to inherit and potentially extend or modify the behavior of the base class. If you find yourself copying and pasting code between classes, inheritance might be a good solution to reduce redundancy.
Memory Footprint
Alternatives
Pros
Cons
FAQ
-
What is the difference between inheritance and composition?
Inheritance is an "is-a" relationship, where a subclass inherits properties and methods from a base class. Composition is a "has-a" relationship, where a class contains an instance of another class. Composition is generally more flexible and avoids the tight coupling associated with inheritance. -
What is method overriding?
Method overriding is when a subclass provides a specific implementation for a method that is already defined in its base class. This allows the subclass to customize the behavior of the inherited method. -
What is the purpose of using super() in Python?
Thesuper()
function is used to call a method from the parent class. It is commonly used in the__init__
method of a subclass to initialize the attributes of the parent class. It helps avoid code duplication and ensures that the parent class's initialization logic is executed.