This article is participating in Python Theme Month, see the event chain for details

takeaway

Recently just learned Java to inheritance and polymorphism always feel not very skilled, in the data outside the search python inheritance polymorphism feel interesting, I will share with you, and Java can be compared with the operation.

inheritance

What is inheritance

  • Of course, the figure above is just a metaphor, but inheritance in code is a concept in object-oriented software technology, along with polymorphism and encapsulation as the three basic characteristics of object-oriented. Inheritance can cause a child class to have properties and methods of its parent class or redefine, append properties and methods, etc. Note: Inheritance in Python is divided into single inheritance and multiple inheritance
  • The purpose of inheritance is to increase the reuse rate of code and reduce the amount of unnecessary code, and as you can see in the figure below, animals have the basic characteristics of cats and dogs, animals are the father, cats and dogs are the children

Inherited characteristics

  • 1. When calling a method of the base class, prefix it with the class name of the base class and take the self argument. Unlike calling normal functions from a class where you don’t need to take the self argument

  • 2. The base class construct (init() method) is not automatically called in inheritance; it needs to be called specifically in the construction of its derived class.

  • 3. Python always looks for methods of the corresponding type first, and if it can’t find them in a derived class, it starts looking one at a time in the base class. Look for the method to call in this class. If you can’t find it, look in the base class.

  • 4, inheritance of the parent class: for the inherited class, called the parent class, also known as the base class, or superclass. Subclass: A class that inherits from another class, called a subclass, also called a derived class.

Single inheritance

  • Python supports class inheritance. Classes mean little if a language does not support inheritance. In this respect, I say in the language fluency is better than to look at the code to the actual. (Personal opinion)

class Animal: # the parent class
    def eat(self) : 
        print(Eat "-- -- -- -- -- -- -- -- -- --")

    def drink(self) :
        print(Drink "-- -- -- -- -- -- -- -- -- --")
        
    def sleep(self) :
        print("Sleep -- -- -- -- -- -- -- -- -- --")


class Dog(Animal) : # Subclass inherits from superclass
    "" def" eat (self) : print (" -- -- -- -- -- for -- -- -- -- - ") def ultimately responds (self) : print (" -- -- -- -- - a -- -- -- -- -- ") def sleep (self) : print (" -- -- -- -- -- to sleep -- -- -- -- -- ") "" "
    pass


class Cat:
    pass


wang_cai = Dog()
wang_cai.eat()
wang_cai.drink()
wang_cai.sleep()# Wang -- CAI inherited how animals eat, drink and sleep
Copy the code

Multilayer inheritance

In a nutshell, this is the relationship: animal – dog – screamers (which is becoming more and more specific) one subclass inherits from the parent and is then inherited by the other subclasses

class Animal:
    def eat(self) :
        print(Eat "-- -- -- -- -- -- -- -- -- --")

    def drink(self) :
        print(Drink "-- -- -- -- -- -- -- -- -- --")


class Dog(Animal) :
    def bark(self) :
        print("----- woof woof ------")


class XTQ(Dog) :
    """ defines a type of screamers. """
    pass
# After inheritance, Croup will "eat", "drink" and "bark".
Copy the code

rewrite

Rewrite the method as the name implies but: the method name remains the same

Such as:


class Animal: # the parent class
    def eat(self) :
        print(Eat "-- -- -- -- -- -- -- -- -- --")

    def drink(self) :
        print(Drink "-- -- -- -- -- -- -- -- -- --")

 
class Dog(Animal) : 
    def bark(self) :
        print("----- woof woof ------")


class XTQ(Dog) : Override the Dog method
    """ defines a type of screamers. """
    def bark(self) :
        print("---- squeal -----")
# Rewrite bark

Copy the code

Multiple inheritance

This is a more clear illustration of multiple inheritance, where one animal inherits both penguin and Erha

The following code:


# Define a superclass
class qi-e:
    def printA(self) :
        print('- the penguins -')

# Define a superclass
class er-ha:
    def printB(self) :
        print('- ha -)

# Define A subclass that inherits from A and B
class C(A,B) :
    def printC(self) :
        print('---- I don't know what it is ----')

obj_C = C()
obj_C.printA()
obj_C.printB()
Copy the code

polymorphism

  • What it does: it allows functions with different functions to use the same function name, so that functions with different content can be called with the same function name.
  • Features: Only care about the object instance method is the same name, do not care about the type of the object; Between the classes to which the object belongs, the inheritance relationship is optional. The advantage of polymorphism can increase the flexibility of external invocation of code, making the code more general and more compatible; Polymorphism is a technique for calling methods without affecting the internal design of the class.
class Duck:
    def quack(self) :
        print("Quaaaaaack!")


class Bird:
    def quack(self) :
        print("bird imitate duck.")


class Doge:
    def quack(self) :
        print("doge imitate duck.")


def in_the_forest(duck) :
    duck.quack()


duck = Duck()
bird = Bird()
doge = Doge()
for x in [duck, bird, doge]:
    in_the_forest(x)
Copy the code

Development:

  • The manifestation of polymorphism in Java: Polymorphism can be understood as multiple forms of the same thing. Polymorphism is also supported in Python, but to a limited extent, mainly because the use of variables in Python is undeclared, so there is no parent class reference to a polymorphic representation of a subclass object, and Python does not support overloading. The use of polymorphism is less obvious in Python than in Java, so it doesn’t make much sense to talk about it deliberately in Python.

conclusion

I think language this kind of thing oneself use which convenient to use which, Java and Python inheritance and polymorphism each has its own advantages and disadvantages, when using or choose their own rest at ease, at the same time, both can also be compared to remember, not to say that a language is good, or learn more points for good in case of use of the search can also save their lives.