Creating a Parent Class in Python
What is a Parent Class?
A parent class (or base class) is a class that provides common attributes and methods that other classes (child classes) can inherit from. It serves as a foundational class from which other classes can derive properties and behaviors. This promotes code reusability and helps in organizing code in a hierarchical manner.
Defining a Parent Class
To define a parent class, you use the class keyword followed by the name of the class and a colon. The class can include an __init__() method for initializing attributes, as well as other methods to define behavior.
Here’s a step-by-step breakdown:
Basic Structure
class ParentClass: pass # This is an empty class, used as a placeholder
- class is the keyword used to define a class.
- ParentClass is the name of the class. By convention, class names are written in CamelCase.
- pass is a placeholder indicating that the class currently has no content.
Adding Attributes and Methods
Attributes are variables that belong to the class, and methods are functions defined within the class. Here’s how to add them:
class Animal: def __init__(self, name, age): self.name = name # Attribute to store the animal's name self.age = age # Attribute to store the animal's age def speak(self): return "The animal makes a sound." # Method to describe the animal's sound
- __init__() is the constructor method that initializes the object’s attributes when an instance is created.
- self refers to the instance of the class and is used to access attributes and methods.
Using Class Attributes
Class attributes are shared by all instances of the class. They can be defined outside of any method:
class Animal: species = "Unknown" # Class attribute def __init__(self, name, age): self.name = name self.age = age
- species is a class attribute that is shared across all instances of Animal.
Instance Attributes
Instance attributes are specific to each instance of the class. They are defined within the __init__() method:
class Animal: def __init__(self, name, age): self.name = name # Instance attribute self.age = age # Instance attribute
- self.name and self.age are instance attributes that store the name and age for each individual Animal instance.
Class Methods and Static Methods
Class methods and static methods can also be defined in a parent class:
- Class Methods: These methods are bound to the class and not the instance. They are defined using the @classmethod decorator and take cls as the first parameter.
class Animal: species = "Unknown" @classmethod def get_species(cls): return cls.species
- Static Methods: These methods do not access or modify class or instance attributes. They are defined using the @staticmethod decorator and do not take self or cls as a parameter.
class Animal: @staticmethod def make_sound(): return "Some generic animal sound."
Inheritance and the Parent Class
When a child class inherits from a parent class, it can access and use all the attributes and methods defined in the parent class. Here’s how it works:
class Dog(Animal): # Dog inherits from Animal def __init__(self, name, age, breed): super().__init__(name, age) # Call the parent class's __init__ method self.breed = breed def speak(self): return "The dog barks."
- Dog inherits from Animal. It can use name and age attributes and the speak() method from Animal.
- super().__init__(name, age) ensures that the __init__ method of Animal is called, initializing name and age.
Example with Additional Details
Here’s a more comprehensive example illustrating a parent class with various features:
class Vehicle: # Class attribute vehicle_type = "General" def __init__(self, brand, model): self.brand = brand # Instance attribute self.model = model # Instance attribute # Instance method def display_info(self): return f"Brand: {self.brand}, Model: {self.model}" # Class method @classmethod def get_vehicle_type(cls): return cls.vehicle_type # Static method @staticmethod def vehicle_info(): return "Vehicles are modes of transportation." # Creating an instance of Vehicle my_vehicle = Vehicle("Toyota", "Corolla") print(my_vehicle.display_info()) # Brand: Toyota, Model: Corolla print(Vehicle.get_vehicle_type()) # General print(Vehicle.vehicle_info()) # Vehicles are modes of transportation.
- Class Attribute: vehicle_type is a class attribute that is shared among all instances.
- Instance Attributes: brand and model are instance-specific attributes.
- Instance Method: display_info() provides information about the specific instance.
- Class Method: get_vehicle_type() returns the class-level attribute.
- Static Method: vehicle_info() provides general information that is not related to class or instance attributes.