Process oriented programming
-
Isn't programming just programming? Why are there so many foreign style word suffixes?? Today we will focus on the following process and object-oriented.
Vernacular version: process oriented programming can be compared to making a dish, so how many steps does a dish consist of??
- Prepare ingredients
- Boil oil
- Discharge auxiliary materials
- Stir fry
- Out of the pot
The most high-end ingredients often only need the simplest cooking method, bah, withdraw Leon. This process, distributed, step-by-step, is process oriented.
If you don't understand, how many steps does it take to put an elephant in the refrigerator? 😢😢😢, Obviously, it's three steps. Open the refrigerator, plug the elephant in and close the refrigerator!
- In fact, process oriented programming is the same. The goal of programming should be realized step by step. Each step is a process!
Example 1:
# The steps of cooking are realized by process oriented programming def step1(): print('The first step is to prepare the ingredients') def step2(): print('The second step is to boil the oil') def step3(): print('The first step is to put auxiliary materials') def step4(): print('The first step is cooking') def step5(): print('The first step is to get out of the pot') def mainstep(): step1() step2() step3() step4() step5() print('Thank the boss and wish him eight sons') mainstep() #result The first step is to prepare the ingredients The second step is to boil the oil The first step is to put auxiliary materials The first step is cooking The first step is to get out of the pot Thank the boss and wish him eight sons
Example 2:
# User registration function ''' 1.Get user name and password 2.Organize into a fixed format 3.File operation write file ''' # Define the function to get user information def get_info(): username = input('please input your name>>>:').strip() pwd = input('please input your pwd>>>:').strip() if len(username) == 0 or len(pwd) == 0: print('your username or name is empty,please try again!') return else: user_id = { '1': 'admin', '2': 'user' } print(user_id) choice = input('please choice your position:') if choice == '1': id = user_id[choice] print('you are admin!') elif choice == '2': id = user_id[choice] print('you are user!') return make_info(username, pwd, id) # Processing information format def make_info(username, pwd, id): data = f'{username}|{pwd}|{id}\n' return save_info(data) # Store to file def save_info(data): with open(r'user_info.txt', 'a', encoding='utf8') as f: f.write(data) print('sign success!') # Call body function get_info() # result please input your name>>>:hammer please input your pwd>>>:123 {'1': 'admin', '2': 'user'} please choice your position:1 you are admin! sign success!
Definition: process oriented programming regards a computer program as a set of commands, that is, the sequential execution of a set of functions. In order to simplify the program design, the process oriented function is continuously divided into sub functions, that is, the large function is cut into small functions to reduce the complexity of the system
1, Object oriented
-
Object oriented, this object is not that object. The core of object-oriented lies in the word "object".
Vernacular version: object-oriented can be understood as that in the process of cooking, we create a robot and write the food preparation and steps into the robot. Then we can understand that the food is the "data" we need, and the steps of how to cook are understood as "functions". This is object-oriented. In general, we define a series of functions to operate the data
-
Object in program: object is the product of integrating data and function, or object is the container of data and function
-
In real life: object is the combination of characteristics and skills
Examples are as follows:
# Before learning object orientation, all data and functions are scattered # data name = 'HammerZe' course = [] # function def add_course(name,course): course.append('python') print(f"student{name}Course selection{course}") add_course(name,course) # result student HammerZe Course selection['python']
In this way, we found that what if 100 students need to and format the output results? 100 times? Is it very troublesome
# Upgrade def add_course(user_info,course): user_info['course'].append(course) print(f"student{user_info['name']}Course selection{user_info['course']}") user_info = { 'name': 'HammerZe', 'course':[], 'add_course':add_course, } user_info['add_course'](user_info,'python') # result student HammerZe Course selection['python'] '''Through integration, the data and functions are written together, and the result is the same'''
Classes and objects
The difference between the two
-
In life
-
Object: the combination of characteristics and skills
-
Class: with similar characteristics, similar skills are classified into one class,
-
For example, watermelon and Hami melon can be classified as one kind of fruit,
​ Dogs and cats can be classified as animals·····
-
Emphasis: from different classification perspectives, the classes may be different. There are objects before classes
-
-
In the program:
- Object: a combination of data and function
- Class: a class with similar data and similar functions
- Emphasis: you must first define the class, and then call the class to generate the object
Define format:
-
Define function
def function name ():
​ pass
-
Define class:
class name ():
​ pass
Analogical memory
Define what happens to the class
- Execute in class code immediately
- Generate a class namespace and throw all the names executed in the class into the namespace (into the big dictionary)
- Bind the namespace of the class to__ dict __, Class name__ dict__ View namespaces
Examples are as follows:
class Student(): def add_course(user_info, course): user_info['course'].append(course) print(f"student{user_info['name']}Course selection{user_info['course']}") print('Calling the class will execute me!!') # View the namespace of the class print(Student.__dict__) # Generate object: an empty object {} is generated when calling the class stu1 = Student() # View the namespace of the object print(stu1.__dict__) # {}
Defines the standard format of the class
Take the student class as an example
class Student(): # initialization def __init__(self,name,age): self.name = name # stu.__dict__['name'] = 'Hammer' self.age = age '''be careful: return You cannot have a return value in this method''' # Course selection method def choose_course(stu_dict,course): stu_dict['course'].append(course) print(f"student{stu_dict['name']}Course selection{course}") stu = Student('HammerZe',18) '''1.The calling class produces an empty object 2.Called Student.__dict__(Empty object,'HmmerZe',18)''' # View the namespace of the class print(Student.__dict__) # View the namespace of the object print(stu.__dict__)# {'name': 'HammerZe', 'age': 18} # Value print(stu.__dict__['name']) print(stu.name)
Find order of attributes
- Property lookup:
- Class attribute: attributes in a class are called class attributes
- Object attributes: attributes are object attributes in the object's own namespace
- be careful:
- Property search: first search from your own object, and then find it in the class that generates the object
If you use dict to obtain a value from the namespace of an object, an error will be reported if it is not found
Use. To get the value, if you can't find it in your own namespace, you will find it in the namespace of the class
- Property search: first search from your own object, and then find it in the class that generates the object
Examples are as follows
class Student(): # initialization school = 'SH' def __init__(self, name, age,course = None): if course is None: course = [] self.name = name # stu.__dict__['name'] = 'Hammer' self.age = age self.course = course '''be careful: return You cannot have a return value in this method''' # Course selection method def choose_course(self, course): self.course.append(course) print(f"student{self.name}Course selection{self.course}") stu = Student('HammerZe', 18) '''1.The calling class produces an empty object 2.Called Student.__dict__(Empty object,'HmmerZe',18)''' ''' Property search: first search from your own object, and then find it in the class that generates the object If used__dict__Get the value from the namespace of the object. If it is not found, an error will be reported use.Get the value. If you can't find it in your own namespace, you will find the namespace of the class ''' # Class lookup # View namespaces print(Student.__dict__) # View values print(Student.school) # SH # View method print(Student.choose_course) # Class addition Student.country = 'China' print(Student.__dict__['country']) # China # Class modification Student.school = 'BJ' print(Student.__dict__['school']) # BJ # Class deletion del Student.school print(Student.__dict__.get('school')) # None ''' The bottom layer is a dictionary, which can be used get ''' # Adding, deleting, querying and modifying objects # View namespaces print(stu.__dict__) # {'name': 'HammerZe', 'age': 18} # View values print(stu.name) # HammerZe # Modify value stu.name = 'Ze' print(stu.name) # Ze # Added value stu.gender = 'male' print(stu.__dict__) # {'name': 'Ze', 'age': 18, 'gender': 'male'} # Delete value del stu.gender print(stu.__dict__) # {'name': 'Ze', 'age': 18} # Method call # Class call Student.choose_course(stu,'python') # Student Ze course selection ['python '] # Object call stu.choose_course('java') # Students Ze choose courses ['python ',' Java ']
-
Note: Methods in classes can be called by classes and objects. However, it is recommended to call objects, because objects will pass themselves as the first parameter to the function