BOBOBK

Python Class Inheritance and Polymorphism

MISCELLANEOUS

In Object-Oriented Programming (OOP), when defining a class, you can inherit from an existing class. The new class is called a Subclass, and the inherited class is called a Base class, Parent class, or Super class.

Format:

SubclassName(ParentClassName):
	pass

Usage Example

class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    pass
class Dog1(Animal):
    def run(self):
        print('Dog is running...')
def run_twice(animal):
    animal.run()
    animal.run()
dog = Dog()
dog.run()    # Output: Animal is running...
dog1 = Dog1()
dog1.run()    # Output: Dog is running..., executes the subclass's own method
run_twice(Animal())
# Output: Animal is running...
# Output: Animal is running...
run_twice(Dog1())
# Output: Dog is running...
# Output: Dog is running...
# Add a new subclass Tortoise, then call the run_twice function, it still works
class Tortoise(Animal):
    def run(self):
        print('Tortoise is running slowly...')
run_twice(Tortoise())    # Calling run_twice function, it still works, just ensure the passed object has a run() method
# Output: Tortoise is running slowly...
# Output: Tortoise is running slowly...

Data Type Judgment

Defining a class is essentially defining a data type, which is exactly the same as Python’s built-in data types, such as str, list, and dict. You can use isinstance() to check if a variable is of a certain type. For isinstance(a, A): If a is an object of class A, it returns true. If a is an object of a subclass of A, it returns true. Otherwise, it returns false.

About Inheritance

  1. Inheritance can put all the functionalities of the parent class directly into the subclass, so you don’t have to start from scratch. The subclass only needs to add its own unique methods, or override and rewrite unsuitable methods from the parent class. Subclasses inherit all methods of the parent class (including the __init__ method; if the parent class’s method has parameters, the subclass must also pass parameters when creating an instance).
  2. When both the subclass and parent class have methods with the same name, the subclass’s method overrides the parent class’s method. During runtime, the subclass’s method will always be called. This is polymorphism.
  3. Inheritance can be multi-level, similar to the relationship from grandparent to parent to child. Any class can ultimately be traced back to the root class object. These inheritance relationships resemble an inverted tree.

About Polymorphism

The caller only needs to call the method, without needing to know the internal details. When a new subclass is added, as long as the method is implemented correctly, there’s no need to modify the original code. In simple terms, no matter how many subclasses are added, there’s no need to modify the existing code. This is the famous “Open/Closed Principle”: Open for extension: Allows subclasses to override methods. Closed for modification: If not overridden, directly inherits the parent class’s method.

Static Languages and Dynamic Languages

If a method requires a parameter that is an object of class A, and the method needs to call the run() method of that parameter: For static languages like Java, you must pass an object of class A or its subclass; otherwise, the method cannot be called. For dynamic languages like Python, you don’t necessarily have to pass an object of class A or its subclass; you just need to ensure that the passed object has a run() method.

This is the dynamic language’s “duck typing” principle: it doesn’t require a strict inheritance hierarchy. An object is considered a “duck” if it “looks like a duck and walks like a duck.”

About file-like objects

Python’s “file-like object” is an example of duck typing. True file objects have a read() method, but many objects that merely have a read() method are considered “file-like objects.” Many functions accept “file-like objects” as parameters, meaning you don’t necessarily have to pass a true file object; you can pass any object that implements the read() method.

Related

Parallelism in One Line of Python Code

TECHNOLOGY
Parallelism in One Line of Python Code

Python has a somewhat notorious reputation when it comes to program parallelization. Technical issues aside, such as thread implementation and the GIL, I believe incorrect teaching guidance is the main problem. Common classic Python multithreading and multiprocessing tutorials often seem "heavy" and tend to scratch the surface without deeply exploring the most useful content for daily work.