Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Object-oriented programming and its three main features


May 30, 2021 Article blog


Table of contents


Programming languages are divided into process-oriented programming, functional programming, and object-oriented programming. In fact, python is an object-oriented programming, so let's first look at their characteristics and disadvantages and what their differences are.

Process-oriented programming: "Procedure Oriented" is a process-centric programming idea. T hese are programmed with what is happening as a goal, unlike object-oriented people who are affected. The obvious difference from object-oriented is encapsulation, inheritance, and class.

Process-oriented programming is most readily accepted by beginners, often with a long piece of code to achieve the specified function, the development process is the idea of data and functions in accordance with the logical order of execution, data and functions separate considerations.

  • Features: Modular process
  • Pros: Performance is higher than object-oriented because class calls require instantiation, overhead, and resource consumption, and performance is the most important factor in process-oriented development for microcontrollers, embedded development, Linux/Unix, and so on.
  • Cons: No object-oriented easy to maintain, easy to reuse, easy to expand

Functional programming: Functional programming is also a way of programming, it regards computer operations as a function of calculation. The most important basis for a function programming language is the lambda calculus, and the function of the calculus can accept the function as input (argument) and output (return value).

Its main idea is to write the operation as much as possible into a series of nested function calls.

Python is not and is unlikely to become a functional programming language, but it supports many valuable functional programming language builds. Some also behave like functional programming mechanisms but have traditionally not been considered to be the construction of functional programming languages.

Python built-in functions: filter(), map(), reduce(), max(), min()

Object-oriented programming: Object-oriented is a systematic way of thinking based on people's understanding of the objective world, using the concept of object (entity) to build a model, simulation of the objective world analysis, design, software implementation methods. Through the concept of object-oriented, computer software systems can correspond to real-world systems one by one.

Object-oriented programming binds data to functions and encapsulates it, allowing for faster development programs and fewer rewrites of duplicate code.

  • Feature: Abstract Encapsulation Inheritance Polymorphism
  • Advantages: Easy to maintain, easy to reuse, easy to expand, because of object-oriented packaging, inheritance, polymorphism characteristics, can design a low-coupling system, make the system more flexible, more easy to maintain
  • Cons: Performance is lower than process-oriented

Can take examples of life to understand the process-oriented and object-oriented, such as five chess, process-oriented design ideas are the first to analyze the steps of the problem: 1, start the game, 2, black first go, 3, draw the picture, 4, judge win or lose, 5, it is Baizi's turn, 6, draw the picture, 7, judge win or lose, 8, return step 2,9, output the final result. Implement each of these steps in a different way.

If it is an object-oriented design idea to solve the problem. O bject-oriented design solves problems from a different perspective. T he whole five chess can be divided into 1, black and white sides, the two sides of the behavior is exactly the same, 2, board system, responsible for drawing the picture, 3, rule system, responsible for determining such as fouls, win or lose and so on. The first category of objects (player objects) is responsible for accepting user input, and inform the second category of objects (checkerboard objects) piece layout changes, chessboard objects receive changes in the pieces will be responsible for showing this change on the screen, while using the third category of objects (rules system) to determine the chess game.

It is clear that object-oriented is a functional division of problems, not steps. T he same is true of drawing chess boards, where such behavior is spread across multiple steps in a process-oriented design, and it is likely that different drawing versions will appear, as designers typically simplify the situation in a variety of ways. I n object-oriented design, the drawing may only appear in the board object, thus ensuring the unity of the drawing.

Three characteristics of object-oriented programming

Before looking at the three main features of object-oriented programming, take a look at the differences between objects and classes.

Objects and classes

A class is a reflection of a real or thought world entity in a computer that encapsulates data and the operations on it. The class is actually a template for creating instances.

Object is a variable with a class type. C lasses and objects are the most basic concepts in object-oriented programming techniques. The object is a concrete example.

How to define a class:

class class(): pass

So how do you convert a class into an object?

Instantiation refers to the process of creating objects with classes as instantiation in object-oriented programming. i s the process of putting an abstract conceptual class into such a physical object. T he instantiation process is generally made up of class names Object names - class names (parameter 1, parameter 2... parameter n) composition.

The construction method init is generally used after the class is defined in contrast to other common methods in that when an object is created, the construction method (also known as the magic method) is called immediately. The contents of the construction method are executed automatically.

1. Package features

Encapsulation, as the name implies, encapsulates the content somewhere and then calls the content that is encapsulated somewhere. Therefore, when using object-oriented encapsulation features, you need to:

  1. Encapsulate the content somewhere
  2. Call the encapsulated content from somewhere, as follows:
  • Call the encapsulated content directly through the object: the object. The property name
  • The encapsulated content is indirectly called by self: self.property name
  • Indirectly invoke encapsulated content through self: self.method name ()

For object-oriented encapsulation, it is actually the use of construction methods to encapsulate the content into the object, and then through the object directly or self indirectly to obtain the encapsulated content.

Examples are as follows:

# 1). 类的定义
class People:
   # 构造方法(魔术方法): 当创建对象时会自动调用并执行;
   # self实质上是实例化出来的对象, e.g: xiaoming, xiaohong;
   def __init__(self, name, age, gender):
      # print("正在创建对象")
       # print(self) # 实质上是一个对象
       # 将创建对象的属性(name, age, gender)封装到self(就是实例化的对象)变量里面;
       # 在类里面定义的变量: 属性
       self.name = name
       self.age = age
       self.gender = gender
   # 在类里面定义的函数: 方法
   def eat(self):
       print('%s eating......' %(self.name))
   def sleep(self):
       # 获取对象self封装的属性(name, age, gender)
       print('%s sleep.......' %(self.name))
# 2). 实例化: 通过类实现对象的创建
xiaoming = People("小明", 20, '男')
# 将对象self/xiaoming封装的属性(name, age, gender)从里面拿出来;
print(xiaoming.name)
xiaoming.eat()
xiaoming.sleep()
xiaohong = People("小红", 20, '女')
print(xiaohong.name)
xiaohong.eat()
xiaohong.sleep()

2, inherit the characteristics

1) Inheritance

Inheritance describes the relationship between things, and when we define a class, we can inherit from an existing class, the new class is called a subclass, an extended class, and the inherited class is called a base class, parent class, or superclass (Baseclass, Superclass).

Question 1: How to achieve inheritance?

When a child class is inherited, when the class is defined, the parent class's name is in parentheses (), for example: class son (father): Here the fatson parent class is.

Question 2: What is the working mechanism of inheritance?

The properties and methods of the parent class are inherited to the child class. For example, if a child class does not define an init method and the parent class does, the method is inherited when the child class inherits the parent class, so as soon as the object is created, the inherited init method is executed by default.

Overriding a parent method: That is, in a child class, there is a method with the same name as the parent class, and the method in the child class overrides the method with the same name in the parent class, and the parent method is overridden.

Method to call the parent class:

  1. In a child class, the parent class name is used directly. T he method name of the parent class ()
  2. Super() Method: python2.2 plus features in the form: super (child class name, self).

2) Multi-inheritance

Multi-inheritance, i.e. child classes have multiple parent classes and have their characteristics.

The difference between a modern class and a classic class:

In Python 2 and previous versions, classes derived from any built-in type are "modern classes" that get all the characteristics of "modern classes" and, conversely, classes that are not derived from any built-in types are called "classic classes".

New classes:

class class name (object):

pass

Classic class:

class name:

pass

The distinction between "modern class" and "classic class" does not exist after Python 3, and versions after Python 3.x, because all classes are derived from the built-in type object (even if the inherited object type is not displayed), i.e. all classes are "modern classes."

The most obvious difference between the two is that they inherit searches in different order, namely:

Classic class multi-inheritance search order (depth-first algorithm): Go deep into the left side of the inheritance tree to find, then return, and start looking for the right.

The new class multi-inheritance search order (breadth-first algorithm): look first horizontally and then up.

The illustration is as follows:

 Object-oriented programming and its three main features1

Examples are as follows:

# python2:
    # 经典类:  class Father:
    # 新式类:   class Father(object):
# python3:
#       所有的都是新式类
# 新式类:  广度优先
# 经典类:  深度优先
class D:
    a = 'd'
class B(D):
    pass
class C(D):
    a = 'c'
class A(B, C):
    pass
obj = A()
print(obj.a)

The result of the run is c, which can be seen as the result of a breadth-first search.

3) Private properties and private methods

By default, properties are "public" in Python, and most OO (object-oriented) languages provide "access controllers" to restrict access to member functions.

In Python, the variable name of an instance becomes a private variable/property if it starts with a double underscore, and the function name of the instance, if it starts with , becomes a private function/method that is accessible only internally and externally.

So must private properties not be accessible from outside?

The python2 version does not have direct access to the property name because the Python interpreter changed the property name to the property name of the class name, so the property name can still be accessed through the property name of the class name. H owever, different versions of the Python interpreter may change the property name to a different variable name, so it is not recommended to use this method to access private properties.

Benefits of private properties and methods:

  1. Ensure that external code does not modify the state inside the object at will, making the code more robust with access restrictions.
  2. What if I want to allow external code to modify properties? Y ou can add a specially set property method to a class. W hy is it so hard? Because in a method, parameters can be checked to avoid passing in invalid parameters.

Examples are as follows:

class Student(object):
    __country = 'china'
    def __init__(self, name, age, score):
        self.name = name
        # 年龄和分数是私有属性
        self.__age = age
        self.__score = score
    # 私有方法, 只能在类内部执行;
    def __modify_score(self, scores):
        self.__score = scores
        print(self.__score)
    def set_age(self, age):
        if 0<age <150:
            self.__age = age
            print("当前年龄:", self.__age)
        else:
            raise  Exception("年龄错误")
    def set_score(self, scores):
        if len(scores) == 3:
            self.__score = scores
        else:
            raise Exception("成绩异常")
class MathStudent(Student):
    pass
student = Student("Tom", 10, [100, 100, 100])
# 在类的外部是不能直接访问的;
print(student.name)
student.set_age(15)
# Python 解释器对外把  __属性名 改成了  _类名__属性名
# print(student._Student__age)

3. Polymorphic properties

Polymorphism literally means "multiple states". I n object-oriented languages, many different implementations of interfaces are polymorphic. In layman's terms: the same operation acts on different objects, can have different interpretations, produce different execution results.

The advantage of polymorphism is that when we need to pass in more children, we just need to inherit the parent class, and the method can either be either either directly undring (i.e., using the parent class) or overriding a specific one. T hat's what polymorphism means. T he caller only calls, regardless of the details, and when we add a new subclass, just make sure that the new method is written correctly, regardless of the original code. T his is the famous "open and closed" principle:

  • Open for extension: Allows subclasses to override method functions
  • Closed for modification: Do not override and directly inherit the parent method function