python inheritance and polymorphism

Posted by hbalagh on Wed, 02 Feb 2022 20:44:32 +0100

One way to create a new class based on an existing class is to let one class directly inherit properties and methods from another class, so as to reduce the writing of repeated code. The class that provides inheritance information is called parent class, also called superclass or base class; The inheritance information we get is called subclass, also known as derived class or derived class. In addition to inheriting the attributes and methods provided by the parent class, subclasses can also define their own unique attributes and methods. Therefore, subclasses have more abilities than the parent class. In actual development, we often replace a parent object with a subclass object, which is a common behavior in object-oriented programming. The corresponding principle is called [Richter replacement principle]( Let's take a look at an example of inheritance.

class Person(object):

    def __init__(self, name, age):
        self._name = name
        self._age = age

    def name(self):
        return self._name

    def age(self):
        return self._age

    def age(self, age):
        self._age = age

    def play(self):
        print('%s Playing happily.' % self._name)

    def watch_av(self):
        if self._age >= 18:
            print('%s Watching a love action movie.' % self._name)
            print('%s Can only watch bear haunt.' % self._name)

class Student(Person):

    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self._grade = grade

    def grade(self):
        return self._grade

    def grade(self, grade):
        self._grade = grade

    def study(self, course):
        print('%s of%s I am learning%s.' % (self._grade, self._name, course))

class Teacher(Person):

    def __init__(self, name, age, title):
        super().__init__(name, age)
        self._title = title

    def title(self):
        return self._title

    def title(self, title):
        self._title = title

    def teach(self, course):
        print('%s%s Talking%s.' % (self._name, self._title, course))

def main():
    stu = Student('Da Chui Wang', 15, 'Junior three')'mathematics')
    t = Teacher('Luo Hao', 38, 'Brick house')
    t.teach('Python Programming')

if __name__ == '__main__':

After a subclass inherits the method of the parent class, it can give a new implementation version of the existing method of the parent class. This action is called method override. Through method rewriting, we can make the same behavior of the parent class have different implementation versions in the subclass. When we call the method rewritten by the subclass, different subclass objects will show different behaviors. This is poly morphism.

from abc import ABCMeta, abstractmethod

class Pet(object, metaclass=ABCMeta):

    def __init__(self, nickname):
        self._nickname = nickname

    def make_voice(self):
        """Make a sound"""

class Dog(Pet):

    def make_voice(self):
        print('%s: Woof, woof...' % self._nickname)

class Cat(Pet):

    def make_voice(self):
        print('%s: Meow...Meow...' % self._nickname)

def main():
    pets = [Dog('Wangcai'), Cat('Katie'), Dog('chinese rhubarb')]
    for pet in pets:

if __name__ == '__main__':

In the above code, we treat the Pet class as an abstract class. The so-called abstract class is a class that cannot create objects. This kind exists specifically for other classes to inherit it. Python does not support abstract classes like Java or C# in terms of syntax, but we can achieve the effect of abstract classes through ABCMeta metaclass and abstractmethod wrapper of abc module. If there are abstract methods in a class, the class cannot be instantiated (create objects). In the above code, the two subclasses of Dog and Cat are respectively used to make in the Pet class_ The voice abstraction method is rewritten and different versions are implemented. When we call this method in the main function, this method shows polymorphic behavior (the same way does different things).

Topics: Python