“A little gesture, please give a follow~”👇
I have once been scarred, I have once wandered far and wide. This is not my desolation, this is my medal. When one day someone asks about my past, I will be proud, not for those scars that have healed, but for the time when I chased my dreams so fiercely.
In Python’s object-oriented programming, inheritance is a core concept that allows us to create new classes based on existing ones. The new class can reuse the properties and methods of the existing class while also extending or modifying these properties and methods. Through inheritance, we can greatly enhance code reusability and maintainability, building a well-structured and clear software system. Next, we will delve into the various details and advanced applications of inheritance in Python.1. Basic Concepts and Syntax of InheritanceThe core idea of inheritance is to create a new class (called a subclass or derived class) that inherits from an existing class (called a superclass or base class). The subclass automatically possesses all the properties and methods of the superclass and can add its own unique properties and methods. In Python, the syntax for defining a subclass is as follows:
class ParentClass:
def __init__(self, attr1):
self.attr1 = attr1
def parent_method(self):
print(self.attr1)
class ChildClass(ParentClass):
def __init__(self, attr1, attr2):
super().__init__(attr1)
self.attr2 = attr2
def child_method(self):
print(self.attr2)
In the above code: 1. First, we define ParentClass, which has a constructor __init__ to initialize the attr1 property and a method parent_method to display the property value. 2. Then we define ChildClass, which inherits from ParentClass, specifying the superclass name in parentheses. 3. In the constructor of ChildClass, we use super().__init__(attr1) to call the constructor of the superclass to initialize the inherited property attr1 while adding its own property attr2. 4. ChildClass also defines a unique method child_method. We can instantiate and call these classes and methods as follows:
child_obj = ChildClass('value1', 'value2')
child_obj.parent_method()
child_obj.child_method()
The output is as follows:
value1
value2
From the result, we can see that the subclass ChildClass can not only call its own defined method child_method but also the method parent_method inherited from the superclass.2. Method OverridingIn the subclass, if a method with the same name as in the superclass is defined, this is called method overriding. When this method is called, the overridden method in the subclass will replace the method in the superclass.
class ParentClass:
def say_hello(self):
print('Hello from ParentClass')
class ChildClass(ParentClass):
def say_hello(self):
print('Hello from ChildClass')
The output is:
child_obj = ChildClass()
child_obj.say_hello()
In the above code, ChildClass overrides the say_hello method in ParentClass. When calling child_obj.say_hello(), the overridden method in the subclass is executed.Calling the Overridden Method in the SuperclassSometimes, in the overridden method of the subclass, we still want to call the method of the superclass with the same name, which can be done using the super() function.
class ChildClass(ParentClass):
def say_hello(self):
super().say_hello()
print('Hello from ChildClass')
The output is:
child_obj = ChildClass()
child_obj.say_hello()
By using super().say_hello(), we called the say_hello method of the superclass in the overridden method of the subclass and extended it.
3. Multiple InheritancePython supports multiple inheritance, meaning a subclass can inherit from multiple superclasses. The subclass will inherit all properties and methods from the superclasses.
class ClassA:
def method_a(self):
print('Method from ClassA')
class ClassB:
def method_b(self):
print('Method from ClassB')
class ClassC(ClassA, ClassB):
def method_c(self):
print('Method from ClassC')
The output is:
class_c_obj = ClassC()
class_c_obj.method_a()
class_c_obj.method_b()
class_c_obj.method_c()
ClassC inherits from both ClassA and ClassB, so it can call methods from both superclasses as well as its own defined methods.Method Resolution Order (MRO)In multiple inheritance, when multiple superclasses have methods with the same name, Python determines which method to call using the Method Resolution Order (MRO). You can view the MRO using the class’s __mro__ attribute.
print(ClassC.__mro__)
The output (may vary slightly between Python versions):
(<class '__main__.classc'="">, <class '__main__.classa'="">, <class '__main__.classb'="">, <class 'object'="">)</class></class></class></class>
This indicates that when looking for a method in ClassC, it will first look in ClassC itself, then in ClassA, ClassB, and finally in object.4. Abstract Base Classes and InheritanceIn Python, you can create abstract base classes (ABC) using the abc module. An abstract base class defines a set of method signatures but does not provide concrete implementations; subclasses must implement these abstract methods.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def area(self):
return 'Area of Rectangle'
class Circle(Shape):
def area(self):
return 'Area of Circle'
The output is:
rectangle = Rectangle()
circle = Circle()
print(rectangle.area())
print(circle.area())
In the above code, Shape is an abstract base class that defines the abstract method area. Rectangle and Circle as subclasses must implement the area method; otherwise, a TypeError will be raised.5. Advanced Applications and Considerations of Inheritance1. Private Attributes and Inheritance:Python does not have strict private attributes, but through naming conventions (e.g., _attr for protected attributes, __attr for “private” attributes), care must be taken during inheritance. Subclasses cannot directly access the __attr attribute of the superclass but can access it indirectly through special means (e.g., _ClassName__attr).2. Inheritance and Polymorphism:Inheritance is the foundation for achieving polymorphism. Through inheritance and method overriding, different subclass objects can respond differently to the same method, thus achieving polymorphism.3. Avoiding Excessive Inheritance:While inheritance can enhance code reusability, excessive use of multiple inheritance can lead to complex and hard-to-maintain code, so it should be used judiciously. Through this in-depth exploration of inheritance in Python, it is believed that you now have a comprehensive understanding of this important object-oriented programming concept. Proper use of inheritance can help us write more efficient, elegant, and maintainable Python code.
“A little gesture, please give a follow~”🫰