Inheritance
Inheritance is a fundamental pillar of object-oriented programming. It allows you to create new classes based on existing classes, reusing and extending their functionality. This way, you can model “is a” relationships (for example, a Dog
is an Animal
).
Why use inheritance?
Section titled “Why use inheritance?”- Code reuse: Avoid repeating common attributes and methods.
- Organization: Allows structuring logical hierarchies between classes.
- Extension: You can add or modify behaviors in subclasses.
Basic syntax
Section titled “Basic syntax”To create a class that inherits from another, simply indicate the base class in parentheses:
class BaseClass: # attributes and methods
class SubClass(BaseClass): # new attributes and methods
Simple example
Section titled “Simple example”Suppose you have an Animal
class and you want to create a Dog
class that inherits from it:
class Animal:def __init__(self, name):self.name = name
def speak(self):print('Makes a sound')
class Dog(Animal):def speak(self):print(f'{self.name} says: Woof!')
my_dog = Dog('Rex')my_dog.speak() # Rex says: Woof!
In this example, Dog
inherits the name
attribute and the speak
method from Animal
, but redefines it to customize the behavior.
Using super()
Section titled “Using super()”You can call methods of the base class using super()
. This is useful for extending functionality without completely replacing it.
class Animal:def __init__(self, name):self.name = name
def describe(self):print(f'I am an animal called {self.name}')
class Cat(Animal):def describe(self):super().describe()print('And I am a cat.')
g = Cat('Michi')g.describe()
Output:
I am an animal called MichiAnd I am a cat.
Multiple inheritance
Section titled “Multiple inheritance”In Python, a class can inherit from multiple classes at the same time:
class ClassA: pass
class ClassB: pass
class SubClass(ClassA, ClassB): pass
Summary
Section titled “Summary”- Inheritance allows you to create classes that reuse and extend others.
- Use
super()
to access methods of the base class. - You can redefine methods to customize the behavior in subclasses.
- Python allows multiple inheritance.
Ready to practice? Try creating a base class Vehicle
and a subclass Car
that adds its own method.