'''
面向过程编程
核心过程而字,过程是解决问题对步骤,即先干啥再干啥后干啥
基于该思想写程序就是在设计一条条对流水线
优点:复杂的问题流程化,进而简单化
缺点:扩展性差
面向对象编程
核心是对象二字,对象是一个用来盛放数据与功能的容器
基于该思想写程序就是在整合程序,
'''
# 1、如何基于面向对象的思想写程序
stu_name = 'egon'
stu_age = 18
stu_gender = 'male'
def choose(stu_name, stu_gender, stu_age):
print(f'{stu_name}:{stu_gender}:{stu_age}正在选课')
choose(stu_name, stu_gender, stu_age)
# 基于对象式的思想进行改写:
def choose(stu_self):
print(f"{stu_self['stu_name']}:{stu_self['stu_age']}:{stu_self['stu_gender']}正在选课")
stu_obj = {
'stu_name': 'egon',
'stu_age': 18,
'stu_gender': 'male',
'choose': choose
}
stu_obj['choose'](stu_obj)
# python提供专门的语法来更漂亮地实现面向对象编程,什么语法?
class Student:
school = 'oldboy'
def choose(self):
print('正在选课!')
stu_obj = Student()
print(stu_obj.school)
'''
学生对象1
数据:
名字 = "冯疯子"
年龄 = 18
性别 = "female"
学生对象2
数据:
名字 = "郭靖"
年龄 = 19
性别 = "male"
学生对象3
数据:
名字 = "大雕"
年龄 = 200
性别 = "male"
学生的类
相同的数据
学校 = "oldboy"
相同的功能
选课
'''
# 类体代码会在类定义阶段立刻执行,然后将产生的名字都丢到类的名称空间中
# 改进1:
class Student:
# 相同的数据
school = "oldboy"
# 相同的功能
def choose(self):
print("正在选课")
# print('====>')
stu_obj1 = Student()
stu_obj2 = Student()
stu_obj3 = Student()
stu_obj1.name = "冯疯子" # stu1_obj1.__dict__["name"] = "冯疯子"
stu_obj1.age = 18
stu_obj1.gender = "female"
stu_obj2.name = "郭靖"
stu_obj2.age = 19
stu_obj2.gender = "male"
stu_obj3.name = "大雕"
stu_obj3.age = 200
stu_obj3.gender = "male"
# print(stu_obj1.name)
# stu_obj1.school = "xxx"
# print(stu_obj1.school)
# print(Student.__dict__)
print(stu_obj1.__dict__)
print(stu_obj2.__dict__)
print(stu_obj3.__dict__)
# 改进2:
class Student:
# 相同的数据
school = "oldboy"
# 相同的功能
def choose(self):
print("正在选课")
stu_obj1 = Student()
stu_obj2 = Student()
stu_obj3 = Student()
def init(obj, x, y, z):
obj.name = x
obj.age = y
obj.gender = z
init(stu_obj1, '疯子', 21, 't')
init(stu_obj2, '傻子', 31, 'm')
init(stu_obj3, '狗子', 12, 'f')
print(stu_obj1.__dict__)
print(stu_obj2.__dict__)
print(stu_obj3.__dict__)
# 改进3:
class Student:
# 相同的数据
school = "oldboy"
# 空对象
def __init__(obj, x, y, z):
obj.name = x
obj.age = y
obj.gender = z
# 相同的功能
def choose(self):
print("正在选课")
# 调用类:
# 1、创建一个空对象与类相关
# 2、把空对象、和参数,一起传给__init__方法,完成对象的初始化
# 3、赋值符号把初始化好的对象的内存地址绑定给变量名stu_obj1
stu_obj1 = Student('峰峰', 12, 'male')
stu_obj2 = Student('寿首', 15, 'male')
stu_obj3 = Student('didi', 22, 'female')
print(stu_obj1.__dict__)
print(stu_obj2.__dict__)
print(stu_obj3.__dict__)
51 面向对象
最新推荐文章于 2024-01-25 15:46:07 发布