Inheritance in Python is a fundamental OOP concept, allowing classes to inherit attributes and methods from a parent class. This promotes code reusability and efficiency by enabling child classes to customize or extend parent class functionalities. Python supports multiple inheritance, enabling a class to derive from more than one base class. Utilize the class ChildClass(ParentClass):
syntax to implement inheritance, where ChildClass inherits from ParentClass, streamlining and organizing code for better maintainability and scalability.
Python Inheritance Syntax
The Python Inheritance Syntax involves defining a new class that inherits properties and behaviors from an existing class. Known as the base or parent class, the existing class provides a foundation. The new class, called the child or subclass, extends or modifies these properties and behaviors. This mechanism facilitates code reuse and hierarchical organization.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Sounds"
class Dog(Animal):
def speak(self):
return "Bark"
Here, Dog inherits from Animal and overrides the speak method to return its specific sound.
Creating A Parent Class
Creating a parent class in Python involves defining a class that serves as a blueprint for child classes. This class encapsulates data and behaviors that are common across various objects. The creation of a parent class promotes code reuse and modularity.
Example:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Brand: {self.brand}, Model: {self.model}")
In this example, Vehicle acts as a parent class with an initializer __init__
to set brand and model attributes, and a method display_info to print these attributes. Child classes can inherit from Vehicle to gain its properties and methods, enabling streamlined and organized code development.
Creating A Child Class
Creating a child class in Python involves extending the functionality of an existing parent class by defining a new class that inherits its properties and methods. This process is pivotal for leveraging polymorphism and encapsulation, key principles of object-oriented programming.
Example:
class ParentClass:
def __init__(self):
self.attribute = "I am a parent attribute"
def method(self):
return "Parent method"
class ChildClass(ParentClass):
def child_method(self):
return "Child method"
In this scenario, ChildClass inherits attribute and method() from ParentClass, and introduces a new method, child_method(). This demonstrates inheritance by allowing ChildClass to utilize and extend the functionality of ParentClass, promoting code reusability and organization.
What Is An Object Class In Python?
An object class in Python is the blueprint from which individual objects are created, encompassing data attributes and methods for interaction. It serves as the foundation for inheritance, allowing derived classes to inherit properties and behaviors from it.
Example:
class Animal:
def speak(self):
return "This animal makes a sound"
class Dog(Animal):
def speak(self):
return "The dog barks"
In this code, Animal is the object class, and Dog is a derived class that inherits from Animal, overriding the speak method to provide a specific implementation.
Subclassing (Calling Constructor Of Parent Class)
Subclassing involves calling the constructor of a parent class to initialize the subclass. This ensures the subclass inherits the parent's properties and behavior.
For example, to inherit from a parent class Vehicle in a subclass Car, you would use.
class Vehicle:
def __init__(self, category):
self.category = category
class Car(Vehicle):
def __init__(self, category, model):
super().__init__(category)
self.model = model
Here, Car calls the constructor of Vehicle, ensuring Car instances have both category and model attributes.
The super() Function
The super() function in Python plays a crucial role in inheritance, enabling derived classes to access methods from their parent class without naming the parent explicitly. This function is pivotal for overriding functionality in child classes, ensuring code reusability and maintainability.
For example, in a class hierarchy where ChildClass inherits from ParentClass, you can use super() to call a method of ParentClass from ChildClass.
class ParentClass:
def __init__(self):
self.value = "Inside ParentClass"
class ChildClass(ParentClass):
def __init__(self):
super().__init__() # Calls ParentClass's __init__()
print(self.value) # Accesses ParentClass's attribute
This example illustrates how super() facilitates the use of parent class methods and attributes within a child class, streamlining inheritance management.
Adding Properties
Adding properties to a class in Python involves defining attributes that are related to the object. In the context of inheritance, child classes can inherit these properties from their parent class, enhancing functionality without duplicating code.
For instance, if Vehicle is a parent class with a property wheels, a child class Car can inherit this property and specify its value.
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
class Car(Vehicle):
def __init__(self, wheels, make):
super().__init__(wheels)
self.make = make
In this example, Car inherits the wheels property from Vehicle and adds another property, make. This demonstrates how inheritance allows for extending and customizing parent class properties in child classes efficiently.
Private Members Of The Parent Class
Private members of the parent class are not directly accessible to the child class in Python. These members have names prefixed with two underscores and no trailing underscores (e.g., __privateVar
). They are intended for internal use within the class and encapsulate data to prevent unintended modifications.
To access private members in a child class, methods within the parent class must be used, which in turn access these private members. Alternatively, name mangling is employed by Python, where __privateVar
in a class named Parent becomes _Parent__privateVar
in the child class, enabling indirect access.
Example:
class Parent:
def __init__(self):
self.__privateVar = "I am private"
def publicMethod(self):
return self.__privateVar
class Child(Parent):
def accessPrivate(self):
# Accessing through a public method of the parent class
return self.publicMethod()
# Create an instance of Child
childInstance = Child()
print(childInstance.accessPrivate()) # Outputs: I am private
This example shows how encapsulation of private members works in inheritance and how they can be accessed safely in Python.