Not object-oriented, don't say you can program (python)

Not object-oriented, don't say you can program (python)

I don't know if you ever thought about what human beings create and learn programming for? If we don't really like programming, our understanding of it is likely to only stay because programming can bring us benefits and program for life. Well, when you really understand the development history of programming language, you will find that programming is essentially just a tool. Of course, the above-mentioned programming for life is not good, but if you rise to the level of human development process, it is indeed a bit one-sided, People who started designing computers didn't actually know that programming languages would appear today. Because the original intention of inventing the computer at that time was actually very simple. It was not so much that people wanted to invent a computer at that time, It's better to say that people wanted to invent a "calculator" at that time "It can help people deal with simple calculation problems that take a long time to calculate manually. Then, in 1946, when the first computer ENIAC came out, it was regarded as the first computer in the real sense. Of course, who invented the first computer? You can search Baidu for different answers to this question, and everyone may have different views It will be different, but it doesn't matter. We just need to know the original intention of inventing the computer and the emergence of later programming. Programming language is a system formed slowly after the advent of computer. After the advent of the computer, if humans want the computer to handle computing tasks for themselves, they must input instructions to it and let the computer do corresponding work according to our instructions. At first, the programming language was called the instruction programming language. Later, because the scale and responsibility of the problems to be handled were increasing, functions, variables These terms are concepts and methods gradually put forward to solve complex programming problems. The programming method at this time is called process oriented programming. In fact, the continuous problems are due to the fact that the computer does not have the same way of thinking. If people want the computer to deal with the work given by people, they must convert people's ideas into machine language recognized by the computer through programming language. If you want to deal with any problem, you need to do such work, which is not only less fun for people, but also a great test for people's intellectual requirements. Not everyone can do such a thing. This is the main reason for the problems such as software crisis. Of course, process oriented programming is not a difficult problem, but using process oriented programming to solve complex problems brings a great test of human thinking and a very low maintainability of the program. People urgently need to find a more suitable programming method.

1. What is object-oriented

Smalltalk language, which was born in the 1970s, gives software developers hope because it introduces a new programming paradigm called object-oriented programming. In fact, when I heard about this name, I wanted to scold the person who took it, because before people came into contact with the word object-oriented, I believe that like me, they are used to the naming rules of nouns. For example, even if it is called object-oriented programming and functional programming (another popular programming method at present), it is easier to see the name and meaning, and it is easy to understand. Object-oriented looks like a verb to me, more like a phrase. I really can't understand this naming method. However, now, I seem to know the real meaning of the name.

What is object-oriented programming? In this way: now we compare the computer to a police dog. Then in the future, we will let the police dog catch suspects and search for drugs. So if object-oriented programming is adopted, the dog at the beginning is a "silly dog" and won't do anything. Let's think about asking it to search for drugs. We need to teach him a set of overall search process, such as moving forward, looking for suspected items, smelling with his nose, analyzing what kind of taste belongs to, judging what kind of thing it is, continuing to search for drugs or calling for drugs, and doing so every time he searches for drugs.

If you use object-oriented programming, even if the dog was a stupid dog at first, We just need to teach such a group of dogs to teach them all the actions they should do (now they have a common name called police dog), and then tell them that it is called drug search. When searching for drugs, we just need to find such a dog first, and then say to search for drugs. It will use its drug search ability to search for drugs. Every time we want to search for drugs, we will find a police dog first (in object-oriented programming, call the police dog class to create a police dog object), and then tell it that we should search for drugs. Moreover, with the long-term evolution of such a dog, the later dog is actually a small police dog, because it has the characteristics of a police dog. Some things can be learned without learning (this is called inheritance, just as blacks are born to run faster than others). Obviously, the object-oriented programming concept is more in line with people's way of thinking, so we can certainly accept the latter way when passing instructions to the computer. Therefore, using object-oriented programming, we need to understand these key parts of speech, object, * encapsulation, inheritance and polymorphism nature

class

Everything is an object, And we can make it contain the same characteristics Objects (static features and dynamic features) are logically classified into one class. The big concept obtained is called class. For example, we call the shape with round shapes as round class. Animals that can walk on two feet, have two hands, need to eat and sleep every day, and can speak are collectively referred to as humans. Entities in the class are called objects, such as Deng in humans Xiangyu is an object, This object has the basic characteristics of human beings (programming generally refers to static characteristics, also known as attributes. For example, the basic attributes of human beings include name, gender, age, etc.) and behavior (it is called a method in programming, for example, human behavior includes eating, sleeping, playing, etc.), and every object in it also has this attribute and method. Then, if you want to ask me to eat, I know how to eat, rather than picking up food, chewing, swallowing, and so on. Therefore, when using this concept in programming, when solving a problem, we first look at the types it needs Objects do their own things, and then get the final desired results according to what these objects do with each other. To put it bluntly, using object-oriented programming is a three-step process.

Three steps of object-oriented programming:

**1. Definition class: * * hump nomenclature is used

Data abstraction: find static features (attributes) related to objects and find nouns

Behavior; Find the dynamic features (Methods) related to the object

2. Manufacturing object

3. Send a message

If you understand the example of police dog I mentioned above, I believe you can easily understand the three-step walk

object

The object is a specific entity of a certain class mentioned above. All things are objects. Of course, the class itself is also an object. For example, the yellow man is an object of human beings, while Deng Xiangyu, a code farmer, is an object of yellow human beings. When programming, we first create classes, Then use the class to find an entity (because only an entity can do specific things), and then send a message to the object (which can be understood as ordering it to do things). The next step is the time to wait for the result. This is the three steps of object-oriented programming mentioned above. Next, we use the simplest example to take you to program the first program with object-oriented programming.

2. Basic examples of object-oriented programming

In python, create a class and use the class keyword. The name of the class should be named in a hump (the beginning letter of each word should be capitalized). For example, the student grade class can be named StudentScore in this way.

Let's create a class called student. We want a student to eat, play games and study. Code is

Step 1: define class

class Student:
    """people"""           # Comment for class

    def __init__(self,name,gender,age):   # Magic method is mainly used to define the attributes of a class. self represents an object
        self.name = name                  # To add an attribute, add self to represent the attribute of the object
        self.gender = gender
        self.age = age

    def eat(self):                          # This method is used to define the class
        """having dinner"""
        print(f'{self.name}be at  table')           # First use print to express the action of eating

    def play(self, game_name):
        """play"""
        print(f'{self.name}Playing{game_name}')

    def study(self, course):  
        """study"""
        print(f'{self.name}I'm learning{course}')

2. Manufacturing object

stu = Student("Li Hua",'male','21')      # Use stu to refer to the object of class Student,
# Just like an interface provided to a user operation object, it is also equivalent to giving the name of the object, just like a = 1, assigning 1 to a

3. Send a message

# Use object Method to send a message to the object
stu.study('python Programming')      # Li Hua is learning python programming
stu.play('Eat chicken')                 # Li Hua is playing and eating chicken
stu.eat()                       # Li Hua is having dinner

Although this seems nothing special, because it is overused here, this is just an example for beginners to better understand object-oriented programming. When you are faced with complex problems, you can see its charm. At that time, the code written directly like before (process oriented) shows its shortcomings.

3. Object oriented three pillars

Encapsulation

Encapsulation for object-oriented programming, it is simply understood that encapsulating the code with classes conceals its internal details, It only provides an interface for users to access (e.g. sending messages to objects). The advantage of this is that when operating objects, we do not need or need to know the method implementation process of objects. We only need to send messages to objects to achieve the purpose, and the encapsulation work is done by others or ourselves. Python has many third-party libraries, which basically have classes and methods encapsulated by others Method, we usually can achieve our goal as long as we can call (send messages to its objects).

Inheritance

Inheritance: extend an existing class to create a new class. This process is called inheritance.

Classes that provide inheritance information are called parent classes (superclasses and base classes), and classes that get inheritance information are called subclasses (derived classes)

In fact, like such a relationship, for example, human beings are a class, yellow people can also be a class, and yellow people are a subclass of human beings, because yellow people are also a kind of human beings. Now, if we want to write the yellow people, we don't need to write everything in the human class. At this time, we can inherit the human class, We get all the things of human beings. Next, we can add our own unique things to it.

Class inheritance example

class Person:           # Parent class
    """people"""

    def __init__(self,name,gender,age):
        self.name = name
        self.gender = gender
        self.age = age

    def eat(self):
        """having dinner"""
        print(f'{self.name}be at  table')

    def play(self, game_name):
        print(f'{self.name}Playing{game_name}')

class Teacher(Person):      # Teachers are also human beings, so teachers can inherit human beings. Just write parentheses after the name of teachers and add the class name to inherit
    """Teacher class"""             # After inheriting this class, you have human properties and methods, and you don't need to write any more
    def __init__(self,name,gender,age,title):             # Plus the unique attribute title of teacher class
        super(Teacher, self).__init__(name,gender,age)          # In super mode, you can avoid writing the definition of name,,, and attributes again
        self.title = title

    def manage(self):                       # Write down the teacher's unique method
        print(f"{self.name}Will manage")


    def work(self,course_name):              # Write down the teacher's unique method (class)
        print(f'{self.name}{self.title}In Teaching{course_name}')


class Student(Person):   
    """student"""

    def __init__(self,name,gender,age,):
        super().__init__(name,gender,age)

    # Behavior abstraction (method)
    def study(self, course_name):
        """study"""
        print(f"{self.name}I'm learning{course_name}")

Now, create teacher and student objects and send them messages

stu = Student('Zhang San',True,20)      # True means "male"
stu.eat()                         # Zhang San is eating
stu.play('King')                   # Zhang San is playing the king
stu.study('python')                  # Zhang San is learning python
             
tea = Teacher('Li Si',False,45,'professor')
print(tea.name)                     # Li Si
tea.play('Eat chicken')                    # Li Si is playing and eating chicken
tea.manage()                       # Li Sihui management
tea.work("mathematics")                    # Professor Li Si is teaching mathematics

Polymorphism

What is polymorphism? For example, teachers have a class behavior, but math teachers and Chinese teachers have different classes. At this time, we can define a class method when creating a teacher class, but we don't implement it. Next, we define another math teacher class and a Chinese teacher class to let them inherit the teacher class. At this time, our math teacher class, A Chinese teacher class has a class teaching method (at this time, it is also called an abstract method, which is only defined but not implemented), but it is not implemented. We need to customize our own class teaching method according to our own requirements in the mathematics teacher class and Chinese teacher class (also called method rewriting, that is, keep the name or the name used in the original parent class, and the implementation steps are rewritten by the child class). Then, the phenomenon that such a method has multiple different implementations is called polymorphism.

The following is an example of a simple wage settlement system

There are three types of employees: Department Manager: fixed monthly salary, 15000 yuan Programmer: Hourly settlement monthly salary, 200 yuan per hour Salesperson: base salary + commission, base salary 1800 yuan, 5% commission on sales

Enter employee information and automatically settle monthly salary

code implementation

"""
example01 - Payroll settlement system
~ Department Manager: fixed monthly salary, 15000 yuan
~ Programmer: Hourly settlement monthly salary, 200 yuan per hour
~ Salesperson: base salary+Commission, base salary 1800 yuan, sales 5%Commission

Enter employee information and automatically settle monthly salary
Author: Ma Nong Deng Xiangyu
Date: 2021/8/6
"""
from abc import abstractmethod    # Import abc module


class WageSytem:
    """Wage settlement"""
    def __init__(self,name,identity):
        self.name = name
        self.identity = identity

    @abstractmethod     # Naming is an abstract method, and abc module needs to be imported
    def calc(self):
        pass


class ManagerWage(WageSytem):
    """Manager salary settlement system"""

    def calc(self):
        return f"{self.name}Your salary this month is{15000}element"

class ProgramerWage(WageSytem):
    """Programmer salary settlement"""

    def __init__(self,name,identity,hour):
        super().__init__(name,identity)
        self.hour = hour

    def calc(self):
        return f"{self.name}Your salary this month is{self.hour * 200}element"

class SalesmanWage(WageSytem):
    """Salesperson salary settlement"""

    def __init__(self,name,identity,sales):
        super().__init__(name,identity)
        self.sales = sales
        self.base_salary = 1800

    def calc(self):
        return f"{self.name}Your salary this month is{self.base_salary + self.sales * 0.05}element"


def main():
    employees_info = [['Zhang San','programmer',160],['Li Si','manager'],['Wang Wu','salesman',20000]]
    for info in employees_info:
        print(info)
        if info[1] == 'programmer':
            print(ProgramerWage(info[0],info[1],info[2]).calc())
        elif info[1] == 'manager':
            print(ManagerWage(info[0],info[1]).calc())
        elif info[1] == 'salesman':
            print(SalesmanWage(info[0],info[1],info[2]).calc())


if __name__ == '__main__':    
    main()

4. Comprehensive example of object-oriented programming

After learning so much, hurry to test your learning achievements with examples!

Poker deal

Use 52 cards (remove the king and Wang) to deal 13 cards to each of the four players

Reference code:

"""
- poker Licensing
 Use 52 cards (remove the king and Wang) to deal 13 cards to each of the four players
Author: Ma Nong Deng Xiangyu
Date: 2021/8/5
"""


from enum import Enum


class Suite(Enum):
    """Decor(enumeration)"""
    SPADE, HEART, CLUB, DIAMOND = range(4)


class Card:
    """brand"""

    def __init__(self, suite, face):
        self.suite = suite
        self.face = face

    def __lt__(self, other):
        if self.suite == other.suite:
            return self.face < other.face
        return self.suite.value < other.suite.value

    def __repr__(self):
        suites = '♠♥♣♦'
        faces = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
        # Get the corresponding characters according to the color and number of cards
        return f'{suites[self.suite.value]}{faces[self.face]}'


import random


class Poker:
    """poker"""

    def __init__(self):
        # Create a list of 52 cards through the generative syntax of the list
        self.cards = [Card(suite, face) for suite in Suite
                      for face in range(1, 14)]
        # The current property indicates the location of the deal
        self.current = 0

    def shuffle(self):
        """shuffle the cards"""
        self.current = 0
        # The random disorder of the list is realized by the shuffle function of random module
        random.shuffle(self.cards)

    def deal(self):
        """Licensing"""
        card = self.cards[self.current]
        self.current += 1
        return card

    @property
    def has_next(self):
        """Are there any cards to deal"""
        return self.current < len(self.cards)


class Player:
    """game player"""

    def __init__(self, name):
        self.name = name
        self.cards = []

    def get_one(self, card):
        """Touch cards"""
        self.cards.append(card)

    def arrange(self):
        self.cards.sort()


poker = Poker()
poker.shuffle()
players = [Player('East evil'), Player('Western poison'), Player('South Emperor'), Player('Northern beggar')]
for _ in range(13):
    for player in players:
        player.get_one(poker.deal())
for player in players:
    player.arrange()
    print(f'{player.name}: ', end='')
    print(player.cards)
    
    
    
# Output results
 East evil: [♠A, ♠2, ♠3, ♠9, ♥3, ♥6, ♥J, ♥K, ♣5, ♣7, ♣9, ♦8, ♦J]
Western poison: [♠6, ♠8, ♠Q, ♠K, ♥5, ♥7, ♥Q, ♣4, ♣6, ♣10, ♦6, ♦9, ♦K]
South Emperor: [♠10, ♥A, ♥9, ♣A, ♣2, ♣3, ♣8, ♦2, ♦3, ♦5, ♦7, ♦10, ♦Q]
Northern beggar: [♠4, ♠5, ♠7, ♠J, ♥2, ♥4, ♥8, ♥10, ♣J, ♣Q, ♣K, ♦A, ♦4]

Output results

East evil:[ ♠ A, ♠ 2, ♠ 3, ♠ 9, ♥ 3, ♥ 6, ♥ J, ♥ K, ♣ 5, ♣ 7, ♣ 9, ♦ 8, ♦ J]
Western poison:[ ♠ 6, ♠ 8, ♠ Q, ♠ K, ♥ 5, ♥ 7, ♥ Q, ♣ 4, ♣ 6, ♣ 10, ♦ 6, ♦ 9, ♦ K]
Nandi:[ ♠ 10, ♥ A, ♥ 9, ♣ A, ♣ 2, ♣ 3, ♣ 8, ♦ 2, ♦ 3, ♦ 5, ♦ 7, ♦ 10, ♦ Q]
North beggar:[ ♠ 4, ♠ 5, ♠ 7, ♠ J, ♥ 2, ♥ 4, ♥ 8, ♥ 10, ♣ J, ♣ Q, ♣ K, ♦ A, ♦ 4]

It's not easy to create. If it helps you, don't forget to like, pay attention to, comment and collect, or give me a small reward!

Keywords: Python Class OOP encapsulation inheritance

Added by jackmn1 on Thu, 30 Dec 2021 10:21:06 +0200