python23__ Object oriented programming (day31)

Posted by kiss_FM on Tue, 18 Jan 2022 04:33:29 +0100

Summary of today's content

  • Process oriented concept
  • Object oriented concept
  • Class definition and object generation
  • Property or method lookup
  • practice

Process oriented

Process oriented:
It's not a technology, it's a programming idea
The core is the process. The process is what to do first, what to do, and what to do last. The mechanic thinks

"""
    Case:
        Put the elephant in the fridge
        1.Open the refrigerator
        2.Put the elephant in
        3.Close the refrigerator door
    Case 2:
    advantage:
        Complex problems are simplified and process oriented
    Disadvantages:
        Poor expansibility and maintainability

    Application scenario: Low scalability requirements

    Question:
        Implement user registration:
            1.Enter user name and password
            2.Validation parameters
            3.register
"""


# 1. Interaction with users
def interactive():
    username = input("Please enter user name:")
    password = input("Please input a password:")
    email = input("Please enter email: ")

    return {
        'username': username,
        'password': password,
        'email': email,
    }


# 2. Validation parameters
def check_info(userinfo):
    is_valid = True

    if len(userinfo['username']) == 0:
        print("User name cannot be empty")
        is_valid = False

    if len(userinfo['password']) == 0:
        print("Password cannot be empty")
        is_valid = False
    if len(userinfo['email']) == 0:
        print("email Cannot be empty")
        is_valid = False

    return {
        'is_valid': is_valid,
        'userinfo': userinfo
    }


# 3. Registration
import json


def register(param):
    if param['is_valid']:
        with open('userinfo', 'w', encoding='utf-8') as f:
            json.dump(param['userinfo'], f)


def main():
    userinfo = interactive()
    checkinfo = check_info(userinfo)
    register(checkinfo)


if __name__ == '__main__':
    main()

Object of class

Class, i.e. category / category, is the cornerstone of object-oriented analysis and design. If multiple objects have similar data and functions, then multiple objects belong to the same category. The advantage of having a class is that we can store the same data and functions of the same class of objects in the class without having to store a copy of each object repeatedly. In this way, each object only needs to store its own unique data, which greatly saves space. Therefore, if an object is a container for storing data and functions, a class is a container for storing the same data and functions of multiple objects.

[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-sk5nQFW4-1626092358780)(%E4%BB%8A%E6%97%A5%E7%AC%94%E8%AE%B0.assets/image-20210712201511382.png)]

To sum up, although we introduce the object first and then the class, it should be emphasized that in the program, we must define the class in advance, and then call the class to generate the object (the return value obtained by calling the class is the object). There is an association between the class that generates the object and the object. This association refers to that the object can access the data and functions common to the class, so the content in the class still belongs to the object. The class is just a mechanism to save space and reduce code redundancy. The ultimate core of object-oriented programming is still to use the object.

After understanding the two core concepts of class and object, we can introduce object-oriented programming.

object-oriented programming

Class definition and instantiation

Taking the development of a course selection system of Tsinghua University as an example, we briefly introduce how to write a program based on object-oriented idea

The basic idea of object-oriented is to integrate the associated data and functions to be used in the program into the object, and then use them. However, there are so many data and functions to be used in the program, how to find the associated data? I need to extract the roles in the course selection system: students, teachers, courses, etc. then it is obvious that students have student related data and functions, and teachers have teacher related data and functions. Let's take students as an example,

"""
object-oriented:
    The core is the word object,
        1.Inside the program
            Objects are containers for data attributes and functions,
        2. In reality
            Object is the combination of characteristics and skills

        Linux: Everything is a document

    Advantages: strong scalability
    Disadvantages: high programming complexity
    Application scenarios: scenarios with high scalability requirements, such as: qq, WeChat

        Case:
            Learning from the West
            Student course selection system
"""


# Version 1:
# stu1_name = 'egon'
# stu2_name = 'tom'
# stu1_age = 18
# stu2_age = 20
# stu1_gender = 'male'
# stu2_gender = 'male'
# stu1_courses = []
# stu2_courses = []
#
# def choose_course(stu_name, stu_courses,course):
#     stu_courses.append(course)
#     print("%s course selected successfully% s"% (stu_name, stu_courses))
#
# choose_ Course (stu1_name, stu1_courses, 'Python whole site development')
# choose_ Course (stu2_name, stu2_courses, 'Linux whole station development')


# # Version 2
#
# stu1 = {
#     'name':'egon',
#     'age' : 18,
#     'gender' : 'male',
#     'courses': []
# }
#
# stu2 = {
#     'name':'tom',
#     'age' : 18,
#     'gender' : 'male',
#     'courses': []
# }
#
#
# def choose_course(stu_dic,course):
#     stu_dic['courses'].append(course)
#     Print ('% s' course selection succeeded% s'% (stu_dic ['name'], stu_dic ['courses'])
#
# choose_course(stu1, 'python whole site development')
# choose_course(stu2, 'linux whole station development')

# Version 3

def choose_course(stu_dic,course):
    stu_dic['courses'].append(course)
    print("%s Successful course selection %s" % (stu_dic['name'], stu_dic['courses']))

stu1 = {
    'name':'egon',
    'age' : 18,
    'gender' : 'male',
    'courses': [],
    'choose_course':choose_course
}

stu2 = {
    'name':'tom',
    'age' : 18,
    'gender' : 'male',
    'courses': [],
    'choose_course':choose_course
}


stu1['choose_course'](stu2, 'python development')
stu2['choose_course'](stu2, 'linux development')

Concept of class

"""
Objects: a combination of features and energy efficiency

Class: a combination of similar characteristics and similar skills of a series of objects

Emphasis: from different angles, the classification is different

Question: class or object first?
    1.In reality:
        There must be an object before there is a class
    2. In the program:
        You must first define a class and generate an object in the calling class
"""

# Define class
"""
class Class name():
    pass
    
    
def Function name():
    pass
    
Class name: generally capitalized
"""

class Student():
    school = 'SH'

    def choose_course(stu_dic, course):
        stu_dic['courses'].append(course)
        print("%s Successful course selection %s" % (stu_dic['name'], stu_dic['courses']))

# Class namespace
print(Student.__dict__)

print(Student.__dict__)
#
#
# # Create an object, call a class, and generate an object
stu1 = Student()  # Calling the class produces an empty object
# stu2 = Student()
#
print(stu1.__dict__)

The process of calling a class is instantiation, and the resulting object is an instance

Custom objects have their own unique properties

# Version 3


"""
    How many things happened to the object?
        1. An empty object is generated and passed as the first parameter
"""

class Student():
    school = 'SH'

    # Initialization method
    def __init__(stu_obj, name, age, gender, courses=[]):
        stu_obj.name = name  # stu1.__dict__['name'] = 'egon'
        stu_obj.age = age  # stu1.__dict__['age'] = 20
        stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'
        stu_obj.courses = courses  # stu1.__dict__['courses'] = []

    def choose_course(stu_dic, course):
        stu_dic['courses'].append(course)
        print("%s Successful course selection %s" % (stu_dic['name'], stu_dic['courses']))


    # print(123)


# Class namespace
# print(Student.__dict__)
stu1 = Student('egon', 18 ,'male')

print(stu1.__dict__)
# stu2 = Student()

# stu1.name = 'egon'      # stu1.__dict__['name'] = 'egon'
# stu1.age = 18           # stu1.__dict__['age'] = 20
# stu1.gender = 'male'    # stu1.__dict__['gender'] = 'male'
# stu1.courses = []       # stu1.__dict__['courses'] = []
#
#
# stu2.name = 'tom'      # stu2.__dict__['name'] = 'egon'
# stu2.age = 18           # stu2.__dict__['age'] = 20
# stu2.gender = 'male'    # stu2.__dict__['gender'] = 'male'
# stu2.courses = []       # stu2.__dict__['courses'] = []


#
# init(stu1, 'egon', 18, 'male')
# init(stu2, 'tom', 18, 'male')
#
#
# print(stu1.__dict__)
# print(stu2.__dict__)

Attribute lookup

class Student():
    school = 'SH'
    # Initialization method
    def __init__(stu_obj, name, age, gender, courses=[]):
        stu_obj.name = name  # stu1.__dict__['name'] = 'egon'
        stu_obj.age = age  # stu1.__dict__['age'] = 20
        stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'
        stu_obj.courses = courses  # stu1.__dict__['courses'] = []

    def choose_course(self, course):
        self.courses.append(course)
        print("%s Successful course selection %s" % (self.name, self.courses))


    # print(123)


# Class namespace
# print(Student.__dict__)
stu1 = Student('egon', 18 ,'male')
stu2 = Student('tom', 18 ,'male')

# print(stu1.__dict__)

# Attribute search of class 1
# print(Student.__dict__['school'])

# # Student.__dict__['xxx'] = 'xxx'
# del Student.__dict__['xxx']

# Student.xxx = 'xxx'
#
# del  Student.xxx

# Student.school = 'MMM'
# print(Student.school)

# print(Student.choose_course)
# Student.choose_course(stu1, 'python')


# The syntax value of the object operation attribute point is taken from its own object first. If not, it is taken from the class
# print(stu1.school)
#
# stu1.xxx = 'x'
# del  stu1.xxx
# stu1.school = 'y'

# Student.school = 'x'
# print(stu1.school)


# The properties in the class are shared with all objects, but the methods in the class are for the object, and the object itself is passed as the first parameter
# stu1.school = 'y'
# print(stu1.school)
#
# print(stu2.school)

stu1.choose_course('python')

Little practice

"""
Define a student class and generate a pile of objects


requirement:
    Add a counter to record how many objects are generated?
"""
class Student():
    school = 'SH'
    # Initialization method
    count = 0

    def __init__(self, name, age, gender, courses=[]):
        self.name = name
        self.age = age
        self.gender = gender
        self.courses = courses
        Student.count += 1

    def choose_course(self, course):
        self.courses.append(course)
        print('%s Successful course selection %s' % (self.name, self.courses))


stu1 = Student('egon', 18, 'male')
stu2 = Student('eva', 21, 'male')
print(Student.count)

print(stu1.count)
print(stu2.count)

print(stu1.__dict__)
print(Student.__dict__

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DNsx3na4-1626092358782)(%E4%BB%8A%E6%97%A5%E7%AC%94%E8%AE%B0.assets/image-20210712164245792.png)]

"""
Define two hero classes,

requirement:
    1. Heroes should have nicknames, health and attack power
    
    2. Generate two objects
    
    3. Attack each other. If the HP is less than 0, it is judged as death

"""

class Hero:

    def __init__(self, name, level, attack):
        self.name = name
        self.level = level
        self.attack = attack

    def action(self, people):
        if people.name == self.name:
            print("You can't attack yourself")
            return

        people.level -= self.attack

        if people.level <= 0:

            print('%s Has been%s Killed' % (people.name, self.name))
            return
        print("%s Attacked%s,%s Remaining%s Health value of" % (self.name,people.name, people.name,people.level))

hero1 = Hero('eva', 100, 50)
hero2 = Hero('wyz', 80, 20)

hero2.action(hero1)
hero1.action(hero2)
hero1.action(hero2)

[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-JeNhWu1x-1626092358784)(%E4%BB%8A%E6%97%A5%E7%AC%94%E8%AE%B0.assets/image-20210712164610733.png)]

Topics: Python