Python正课67 —— 面向对象介绍

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12651807.html

一:面向过程 与 面向对象

面向过程:

核心是‘过程’二字
过程的终极奥义:将程序流程化
过程是‘流水线’,用来分步骤解决问题的

面向对象:

核心是‘对象’二字
对象的终极奥义:将程序‘整合’
对象是‘容器’,用来盛放 数据 与 功能的

程序 = 数据 + 功能

二:实现方法

初级版

# 学生的数据
stu_name = 'xxq'
stu_age = 18
stu_gender = 'male'


# 学生的功能
def tell_stu_info():
    print(f'学生信息 - 名字:{stu_name} 年龄:{stu_age} 性别:{stu_gender}')


# 课程的数据
course_name = 'python'
course_period = '6month'
course_score = 10


# 课程的功能
def tell_course_info():
    print(f'课程信息 - 名称:{course_name} 周期:{course_period} 学分:{course_score}')


def set_info():
    global stu_name
    global stu_age
    global stu_gender

    stu_name = 'egon'
    stu_age = 80
    stu_gender = 'female'

    tell_stu_info()


set_info()

进阶版

# 学生的功能
def tell_stu_info(stu_obj):
    print('学生信息 - 名字:%s 年龄:%s 性别:%s' % (
        stu_obj['stu_name'],
        stu_obj['stu_age'],
        stu_obj['stu_gender']
    ))


def set_info(stu_obj, x, y, z):
    stu_obj['stu_name'] = x
    stu_obj['stu_age'] = y
    stu_obj['stu_gender'] = z
    # stu_name = 'egon'
    # stu_age = 80
    # stu_gender = 'female'


stu_obj = {
    'stu_name': 'xxq',
    'stu_age': 18,
    'stu_gender': 'male',
    'tell_stu_info': tell_stu_info,
    'set_info': set_info,
}

print(stu_obj)

高级版

# 学生的功能
def tell_stu_info(stu_obj):
    print('学生信息 - 名字:%s 年龄:%s 性别:%s' % (
        stu_obj['stu_name'],
        stu_obj['stu_age'],
        stu_obj['stu_gender']
    ))


def set_info(stu_obj, x, y, z):
    stu_obj['stu_name'] = x
    stu_obj['stu_age'] = y
    stu_obj['stu_gender'] = z
    # stu_name = 'egon'
    # stu_age = 80
    # stu_gender = 'female'


stu_obj = {
    'stu_school': 'oldboy',
    'stu_name': 'xxq',
    'stu_age': 18,
    'stu_gender': 'male',
    'tell_stu_info': tell_stu_info,
    'set_info': set_info,
}

stu1_obj = {
    'stu_school': 'oldboy',
    'stu_name': 'qwe',
    'stu_age': 18,
    'stu_gender': 'female',
    'tell_stu_info': tell_stu_info,
    'set_info': set_info,
}

print(stu_obj)
posted @ 2020-04-07 10:21  轻描丨淡写  阅读(275)  评论(0编辑  收藏  举报