Day27.产生对象
1.产生对象
# 一.先定义类:存放共有的部分 # 类是对象相似数据与功能的集合体 # 所以类中最常见的是变量与函数的定义,但是类体其实是可以包含任意其他代码的 # 注意:类体代码是在类定义阶段就会立即执行,会产生类的名称空间 class Student: # 1.变量的定义 stu_school = 'oldboy' # 2.功能的定义 # 学生的功能 def tell_stu_info(stu_obj): print('学生信息:名字:{} 年龄:{} 性别:{}'.format( 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 # print('==========> ') # print('__dict__方法,查看类中所有的值'.center(40,'=')) # print(Student.__dict__) # print('') # print('属性访问的语法,用法:`类.属性`'.center(60, '=')) # print('__dict__方法,访问数据属性'.center(40,'=')) # print(Student.__dict__['stu_school']) # print('__dict__方法,访问函数属性'.center(40,'=')) # print(Student.__dict__['set_info']) # print('') print('往类中增加属性值'.center(40, '=')) Student.x = 111 # Student.__dict__['x'] = 111 print(Student.__dict__) print('') # 二.再调用类产生对象 stu1_obj = Student() stu2_obj = Student() stu3_obj = Student() print('往类中存放数据'.center(40, '=')) # 为对象定制自己独有的属性 # 问题1:代码重复 # 问题2:属性的查找顺序 # 简化后:使用`类.属性`存放数据 # 底层执行原理: stu1_obj.stu_name = 'egon' # stu1_obj.__dict__['stu_name'] = 'egon' stu1_obj.stu_age = 18 # stu1_obj.__dict__['stu_age'] = 18 stu1_obj.stu_gender = 'male' # stu1_obj.__dict__['stu_gender'] = 'male' print(stu1_obj.__dict__) stu2_obj.stu_name = 'lili' stu2_obj.stu_age = 19 stu2_obj.stu_gender = 'female' print(stu2_obj.__dict__) stu3_obj.stu_name = 'jack' stu3_obj.stu_age = 20 stu3_obj.stu_gender = 'male' print(stu3_obj.__dict__)