Discussion on Python object oriented programming oop

  • 2021-11-29 08:03:12
  • OfStack

It took several hours to popularize the knowledge of OOP for my little cousin, so I simply summarized and wrote an article.

OOP Full name Object Oriented Programming

Object-oriented programming, or OOP, is so oddly called because the concept is not born out of thin air, but rather as opposed to "process-oriented programming."

To understand what process-oriented is, we should start with the earliest original programming that is neither object-oriented nor process-oriented.

Ancient times

In the earliest ancient times of programming, programs were simply executed in sequence:


print("dosometing")
a=int(input())
b=int(input())
result=a+b
print("{}+{}={}".format(a,b,result))
print("dosomething")

This involves a question. If a certain part of the code needs to be executed repeatedly, such as the code that inputs two numbers and prints the result above, what if this logic needs to be executed again? Do you want to write it again?

Some languages, such as C, do this:


print("dosometing")
a=int(input())
b=int(input())
result=a+b
print("{}+{}={}".format(a,b,result))
print("dosomething")
goto 2

Here only use python pseudo-code to represent the writing of C language, this code can not really be executed.

The C language can be used goto Statement disturbs the compiler's logic of "executing code sequentially" and forces the compiler to jump to the specified line of code to execute code.

It seems to solve the problem, but this brings another problem, which is frequently used goto Statement will break the most basic rule of "sequential execution of code", and greatly reduce the readability and maintainability of code. Not to mention letting other programmers read such code, even the author himself will have a headache when reading it every few months.

So there is "process-oriented programming".

Process-oriented programming

Process-oriented mainly solves the above problem of "code reuse", encapsulating the code fragment that needs to be reused into a function, which can be reused by simple function call:


def input_and_print():
    a = int(input())
    b = int(input())
    result = a+b
    print("{}+{}={}".format(a, b, result))
print("dosometing")
input_and_print()
print("dosomething")
input_and_print()

It seems that the problem has been solved, and there is no big problem. If all we have to solve is the pediatric problem of "inputting two numbers and adding them to output one result", of course, this is true, but the programming world is obviously not so simple.

Suppose we need to use a program to simulate a "simple" beverage machine. If we are programming for the process, we may write as follows:


STATUS_READY = 0
STATUS_COINED = 1
def coin(now_status):
    if now_status == STATUS_READY:
        print(" Input 1 A coin ")
        return STATUS_COINED
    else:
        print(" Coins have been put in ")
        return now_status
def get_drink(now_status):
    if now_status == STATUS_COINED:
        print(" Spit out 1 Bottle of drink ")
        return STATUS_READY
    else:
        print(" Please put in coins first ")
        return now_status
machine_status = STATUS_READY
machine_status = get_drink(machine_status)
machine_status = coin(machine_status)
machine_status = get_drink(machine_status)

It seems that this code is not bad, but there are still many problems. For example, because the function can't save the "state", we can only set a variable outside the function machine_status Represents the status of the beverage machine and is passed as a parameter every time the function is called.

This has two disadvantages:

The function representing the function of the beverage machine and the data representing the state of the beverage machine are separated. Both of them should have been part 1 of the beverage machine, but now they are two unrelated parts. Function has no way to directly modify the status of the beverage machine (of course, it is not completely absent, such as using global Or pass in 1 object parameter, but these unconventional means are not discussed here).

In order to solve these problems, there is object-oriented programming.

Object-oriented programming

Let's see how to write a beverage machine if it is object-oriented programming:


from enum import Enum
from enum import Enum
class MachineStatus(Enum):
    READY=1
    COINED=2
class DrinkMachine:
    def __init__(self) -> None:
        self.status=MachineStatus.READY    
    def coin(self):
        if self.status == MachineStatus.READY:
            print(" Input 1 A coin ")
            self.status = MachineStatus.COINED
        elif self.status == MachineStatus.COINED:
            print(" Has been invested 1 A coin ")
        else:
            print(" Unknown error ")    
    def get_drink(self):
        if self.status == MachineStatus.COINED:
            print(" Spit out 1 Bottle of drink ")
            self.status=MachineStatus.READY
        elif self.status == MachineStatus.READY:
            print(" Please put in first 1 A coin ")
        else:
            print(" Unknown error ")
dm = DrinkMachine()
dm.get_drink()
dm.coin()
dm.get_drink()

It can be seen that the concept of "beverage machine" is a whole, including the state and functions provided by the beverage machine, and the state change of the beverage machine is completely encapsulated in the object, so the "user" does not need to worry about the state change, just call the method of the object as needed.

What is OOP?

Now let's go back to the title, what exactly is OOP? In fact, objects are not a programming-specific concept, just as design patterns come from buildings, objects are also a concept from the real world.

In the real world, when we do a thing, it often revolves around a thing entity. For example, when driving out, you must first have a car, four tires, an engine and a car full of oil. This is a real thing. Corresponding to OOP, it is like the data that makes up the object. The functions provided by this car, such as carrying people, pulling goods and driving, are all the functions provided by the car. The corresponding OOP is the method owned by the object. This is obviously a way of thinking in line with human habits, that is, thinking around things (objects).

Process-oriented is not so consistent with human common sense. It only pays attention to process (function), that is, as long as it can carry people or pull goods, it doesn't pay much attention to whether you use a private car or a tank.

Therefore, OOP is a method to think and solve problems used for reference in the programming field, which is an idea, and encapsulation, inheritance and polymorphism are the means and technical details to realize this idea concretely.


Related articles: