base class
In object-oriented programming (OOP), a base class, also known as a superclass or parent class, is a class from which other classes, known as derived or child classes, inherit attributes (data) and methods (behaviors).
Base classes encapsulate common attributes and methods in a hierarchy, which allows for code reuse. This means you can write more modular and maintainable code, with the advantage that changes to the base class will propagate to its subclasses.
You can also turn a base class into abstract base class as a way to enforce a common interface (API) across different classes, ensuring that they implement certain methods and attributes.
Example
Here’s a simple example of a base class in Python:
vehicles.py
class MotorVehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f"The {self.brand} {self.model}'s engine is starting!")
class SelfDrivingCar(MotorVehicle):
def self_drive(self):
print("Self-driving through the road!")
# Usage
car = SelfDrivingCar("Waymo", "One")
car.start_engine() # Output: The Waymo One's engine is starting!
car.self_drive() # Output: Self-driving through the road!
In this example, MotorVehicle
is a base class with a method .start_engine()
that is common to all the possible derived motor vehicles. The SelfDrivingCar
class inherits from MotorVehicle
and extends it with the .self_drive()
method to provide a concrete feature.
Related Resources
Tutorial
Python Classes: The Power of Object-Oriented Programming
In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.
For additional information on related topics, take a look at the following resources:
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)