python object-oriented -- encapsulation, inheritance, polymorphism

Posted by mattwade on Thu, 20 Jan 2022 02:11:33 +0100

Introduction to basic knowledge

1. Packaging

Encapsulation refers to putting the implementation codes of data and specific operations inside an object so that the implementation details of these codes are not discovered by the outside world. The outside world can only use the object through the interface, but cannot modify the internal implementation of the object in any form. It is precisely due to the encapsulation mechanism, When a program uses an object, it does not need to care about the details of the object's data structure and the method of realizing the operation.

  • Using encapsulation can hide object implementation details and make the code easier to maintain,
  • At the same time, because the private information inside the object can not be called or modified directly, the system security is guaranteed to a certain extent.
  • Class encapsulates functions and variables internally to achieve a higher level of encapsulation than functions.
    class Student:
        classroom = '101'
        address = 'beijing' 
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def print_age(self):
            print('%s: %s' % (self.name, self.age))
    
    
    # The following is the wrong usage
    # Class encapsulates its internal variables and methods to prevent direct external access
    print(classroom)
    print(adress)
    print_age()

2. Succession

Inheritance comes from the real world. The simplest example is that children will have some characteristics of their parents, that is, each child will inherit some characteristics of their father or mother. Of course, this is only the most basic inheritance relationship. There are more complex inheritance in the real world. The inheritance mechanism realizes the reuse of code. The common code part of multiple classes can only be provided in one class, while other classes only need to inherit this class.

In OOP programming, when we define a new class, the new class is called Subclass, and the inherited class is called Base class, parent class or Super class. The greatest advantage of inheritance is that while the Subclass obtains all the variables and methods of the parent class, it can be modified and expanded as needed. Its syntax structure is as follows:

Python supports the inheritance mechanism of multiple parent classes, so you need to pay attention to the order of base classes in parentheses. If the base class has the same method name and is not specified when the subclass is used, python will search from left to right whether the base class contains the method. Once it is found, it will be called directly and will not continue to find later.

# Parent class definition
class people:

    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.__weight = weight

    def speak(self):
        print("%s say: I %d Years old." % (self.name, self.age))

# Single inheritance example
class student(people):

    def __init__(self, name, age, weight, grade):
        # Call the instantiation method of the parent class
        people.__init__(self, name, age, weight)
        self.grade = grade

    # Override the speak method of the parent class
    def speak(self):
        print("%s say: I %d Years old, I'm reading %d grade" % (self.name, self.age, self.grade))

s = student('ken', 10, 30, 3)
s.speak()

 

The inheritance mechanism of Python 3 is different from that of Python 2. Its core principles are the following two, please remember!

  • When a subclass calls a method or variable, it first looks inside itself. If it is not found, it starts to look in the parent class according to the inheritance mechanism.
  • Find the parent classes one by one in a depth first manner according to the order in the parent class definition!

super() function:

As we all know, if there is a member with the same name as the parent class in the child class, the member in the parent class will be overwritten. What if you want to force the members of the parent class to be called? Use the super() function! This is a very important function. The most common is to call the instantiation method of the parent class through super__ init__  !

Syntax: Super (subclass name, self) Method name (), the subclass name and self need to be passed in, the methods in the parent class need to be called, and the parameters need to be passed in according to the methods of the parent class.

class A:
    def __init__(self, name):
        self.name = name
        print("Parent class__init__Method was executed!")
    def show(self):
        print("Parent class show Method was executed!")

class B(A):
    def __init__(self, name, age):
        super(B, self).__init__(name=name)
        self.age = age

    def show(self):
        super(B, self).show()

obj = B("jack", 18)
obj.show()

 3. polymorphic

class Animal:

    def kind(self):
        print("i am animal")


class Dog(Animal):

    def kind(self):
        print("i am a dog")


class Cat(Animal):

    def kind(self):
        print("i am a cat")


class Pig(Animal):

    def kind(self):
        print("i am a pig")

# This function takes an animal parameter and calls its kind method
def show_kind(animal):
    animal.kind()


d = Dog()
c = Cat()
p = Pig()

show_kind(d)
show_kind(c)
show_kind(p)

------------------
Print results:

i am a dog
i am a cat
i am a pig

Dogs, cats and pigs all inherit animal classes and rewrite the kind method respectively. show_ The kind () function takes an animal parameter and calls its kind method. It can be seen that whether we pass a dog, cat or pig to animal, we can correctly call the corresponding methods and print the corresponding information. This is polymorphism.

In fact, due to the dynamic language characteristics of Python, it is passed to the function show_ The parameter animal of kind() can be of any type, as long as it has a kind() method. When a dynamic language calls an instance method, it does not check the type. As long as the method exists and the parameters are correct, it can be called. This is the "duck type" of dynamic language. It does not require a strict inheritance system. As long as an object "looks like a duck and walks like a duck", it can be regarded as a duck

Reference link

Topics: Python Class