Python正课68 —— 实现面向对象编程

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

Python中的面向对象语法

类 是对象相似数据 与 功能的 集合体

所以,类中最常见的是变量 与 函数 的定义,但是 类体中 其实是可以包含任意其他代码的

注意:类体代码 是在 类定义阶段就会立即执行的

class Student:
    # 1.变量的定义
    stu_school = 'oldboy'

    # 2.功能的定义
    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

    # print('=======>')
    
# 属性访问的语法
# 1.访问数据属性
# 2.访问函数属性
# print(Student.__dict__)         # {'__module__': '__main__', 'stu_school': 'oldboy', 'tell_stu_info': <function Student.tell_stu_info at 0x035B8418>, 'set_info': <function Student.set_info at 0x035B83D0>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
# print(Student.stu_school)       # oldboy

# 再调用类产生对象
stu1_obj = Student()
stu2_obj = Student()
stu3_obj = Student()

# stu1_obj.__dict__['stu_name'] = 'eogn'
# stu1_obj.__dict__['stu_age'] = 16
# stu1_obj.__dict__['stu_gender'] = 'male'
# print(stu1_obj.__dict__)        # {'stu_name': 'eogn', 'stu_age': 16, 'stu_gender': 'male'}

stu1_obj.stu_name = 'eogn'
stu1_obj.stu_age = 16
stu1_obj.stu_gender = 'male'
print(stu1_obj.__dict__)        # {'stu_name': 'eogn', 'stu_age': 16, 'stu_gender': 'male'}
posted @ 2020-04-07 16:31  轻描丨淡写  阅读(276)  评论(0编辑  收藏  举报