MON. object-oriented programming

MON. object-oriented

Process oriented programming

  • Process oriented is not a technology, but a programming idea
  • advantage
    • Complex problems are simplified and process oriented
  • shortcoming
    • Poor scalability

object-oriented programming

  • A programming idea

  • The core is the word "object"
  • Objects are "containers" that hold data and functions

  • The ultimate meaning of object is to highly "integrate" data and functions (the higher the degree of "integration", the higher the degree of decoupling of programs)
  • Container ≈ program = data + function

  • advantage

    • Strong expansibility
  • shortcoming

    • High programming complexity
1. .py file
# data
a = 1
b = 0

# function
def sum(x, y):
    return x + y

2. Dictionary, list, tuple, set
# function
def sum(x, y):
    return x + y

# Container, object
sum_obj = {'x': 1,
           'y': 2,
           'sum': sum}

# What language does Python provide to allow us to integrate data and functions well
3.Python Object mechanism in
 class -- Classify objects,It is used to store data and functions shared by similar objects

The core of object-oriented programming is still to use objects

Object oriented underlying principle

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')

"""
Whoever calls it will pass it in as the first parameter, that is, the underlying principle of object-oriented
"""

class

  1. Class is a collection of similar data and functions of objects

  2. The most common class body is the definition of variables and functions, but the class body can contain any other code

  3. Note: the class body code will be executed immediately in the class definition stage, and the class namespace will be generated
  4. Classes store the data or function space shared by objects. In essence, they serve objects, but classes can also call them themselves

Define class

  1. The class body code is executed immediately during the class definition phase
  2. Generates the namespace of the class
  3. Bind the class namespace to the class name
  • Class names are generally capitalized
class Student:
    # Define variables
    stu_school = 'oldboy'
    
    # Define function
    def tell_stu_info(stu_obj):
        print('Student information: name: %s, Age: %s, Gender: %s' % (
          stu_obj['stu_name'],
          stu_obj['stu_age'],
          stu_obj['stu_gender']))
    def tell_stu_info(stu_obj):
        stu_obj['stu_name']=x
        stu_obj['stu_age']=y
        stu_obj['stu_gender']=z
    print('======>')

Syntax for property access

1. print(Student.__dict__)

2. 
# Access data properties
print(Student.stu_school)

# Access function properties
print(Student.set_info)

Call class to generate object

  • Class calls do not execute class body code, only generate objects and establish associations
# Customize your own unique properties for objects
1. Method 1
stu_obj.__dict__['stu_name']='jason'
stu_obj.__dict__['stu_age']=18
stu_obj.__dict__['stu_gender']='male'
print(stu_obj.__dict__)

"""
__dict__ Find only inside objects,No lookup to class,If the value to be taken is not inside the object,An error is reported directly
"""

2. Method 2
Student.stu_name='egon'
Student.stu_age=18
Student.stu_gender='male'
print(stu_obj.__dict__)

"""
However, there are two problems to be solved
1. Code redundancy,Too many repetitions
2. Attribute lookup priority
"""

3. Method 3
def init(stu_obj, name, age, gender):
    stu_obj.name = name
    stu_obj.age = age
    stu_obj.gender = male
    stu_obj.courses = courses
    
# Optimize -- > initialization method 16:00
def __init__(self, name, age, gender):
    self.name=name
    self.age=age
    self.gender
    self.courses=courses

Several things happened to the object

  1. Generate an empty object
  2. Pass the empty object as the first parameter

Unique properties of custom objects

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__)

Property lookup for class

'''Add and change properties of class'''
# If it exists, you can find or modify it. If it does not exist, you can add it
1.__dict__method
Student.__dict__['xxx']='xxx'

2.'.'Syntax value(recommend)
Student.xxx='xxx'

'''Class'''
1.__dict__method
print(Student.__dict__['xxx'])

2.'.'Syntax value
print(Student.xxx)

'''Class'''
1.__dict__method
del Student.__dict__['xxx']

2.'.'grammar
del Student.xxx
  • Object operation properties, '.' Syntax value, first from the object, if not, then from the class

  • The properties in the class are shared with all objects, and the methods in the class are used for the object, and the object itself is passed as the first parameter. However, the object's properties are unique, and changes to the object's properties only apply to the current object

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

Added by stressedsue on Thu, 20 Jan 2022 05:32:39 +0200