16 面向对象 01

目录:

一、面向对象编程思想介绍

二、类与对象介绍

三、类的定义与对象的产生

四、__init__方法

五、属性查找

 

一、面向对象

1.面向过程

面向过程的程序设计:核心是过程二字,过程指的是解决问题的步骤,即先干什么再干什么......面向过程的设计就好比精心设计好一条流水线,是一种机械式的思维方式。

优点是:复杂度的问题流程化,进而简单化(一个复杂的问题,分成一个个小的步骤去实现,实现小的步骤将会非常简单)

缺点是:一套流水线或者流程就是用来解决一个问题,生产汽水的流水线无法生产汽车,即便是能,也得是大改,改一个组件,牵一发而动全身。

应用场景:一旦完成基本很少改变的场景,著名的例子有Linux內核,git,以及Apache HTTP Server等。

# 1. 用户输入数据
def interactice():
    username = input("请输入用户名:>>").strip()
    password = input("请输入密码:>>").strip()

    return {
        'username': username,
        'password': password,
    }


# 2. 验证参数
def check_info(userinfo):
    """
    userinfo= {
        'username':username,
        'password':password,
    }
    :param userinfo:
    :return:
    """
    is_valid = True
    if len(userinfo['username']) == 0:
        print("用户名必须填写")
        is_valid = False

    if len(userinfo['password']) == 0:
        print("password必须填写")
        is_valid = False

    return {
        'is_valid': is_valid,
        'userinfo': userinfo
    }


# 3. 写入数据,注册成功
def register(param):
    """
    :param={
        'is_valid':is_valid,
        'userinfo':userinfo
    }
    :param param:
    :return:
    """
    import json
    if param['is_valid']:
        with open('userinfo', 'w', encoding='utf-8') as f:
            json.dump(param['userinfo'], f)


def main():
    # 1.接收用户信息
    userinfo = interactice()  # {}

    # 2. 验证参数
    info = check_info(userinfo)

    # 3. 注册
    register(info)


if __name__ == '__main__':
    main()

 

2.面向对象

面向对象的程序设计:核心是对象二字,对象是特征与技能的结合体,基于面向对象设计程序就好比在创造一个世界,你就是这个世界的上帝,存在的皆为对象,不存在的也可以创造出来,与面向过程机械式的思维方式形成鲜明对比,面向对象更加注重对现实世界的模拟,是一种“上帝式”的思维方式。

缺点: 编程的复杂度高

优点:扩展性强,可维护性强

应用场景:需求经常变化的软件,一般需求的变化都集中在用户层,互联网应用,企业内部软件,游戏等都是面向对象的程序设计大显身手的好地方。如:微信、qq

二、类与对象的介绍

对象是特征与技能的结合体

类则是一系列对象相同的特征与技能的结合体。

注意:站在不同的角度,划分的分类不一定一样

在现实世界中:先有对象,再有类

在程序中:务必保证先定义类,后产生对象

 

  PS:
    1. 在程序中特征用变量标识,技能用函数标识
    2. 因而类中最常见的无非是:变量和函数的定义

#方式一、为对象初始化自己独有的特征
class People:
    country='China'
    x=1
    def run(self):
        print('----->', self)

# 实例化出三个空对象
obj1=People()
obj2=People()
obj3=People()

# 为对象定制自己独有的特征
obj1.name='egon'
obj1.age=18
obj1.sex='male'

obj2.name='lxx'
obj2.age=38
obj2.sex='female'

obj3.name='alex'
obj3.age=38
obj3.sex='female'

# print(obj1.__dict__)
# print(obj2.__dict__)
# print(obj3.__dict__)
# print(People.__dict__)





#方式二、为对象初始化自己独有的特征
class People:
    country='China'
    x=1
    def run(self):
        print('----->', self)

# 实例化出三个空对象
obj1=People()
obj2=People()
obj3=People()

# 为对象定制自己独有的特征
def chu_shi_hua(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
    obj.name = x
    obj.age = y
    obj.sex = z

chu_shi_hua(obj1,'egon',18,'male')
chu_shi_hua(obj2,'lxx',38,'female')
chu_shi_hua(obj3,'alex',38,'female')





#方式三、为对象初始化自己独有的特征
class People:
    country='China'
    x=1

    def chu_shi_hua(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
        obj.name = x
        obj.age = y
        obj.sex = z

    def run(self):
        print('----->', self)


obj1=People()
# print(People.chu_shi_hua)
People.chu_shi_hua(obj1,'egon',18,'male')

obj2=People()
People.chu_shi_hua(obj2,'lxx',38,'female')

obj3=People()
People.chu_shi_hua(obj3,'alex',38,'female')




# 方式四、为对象初始化自己独有的特征
class People:
    country='China'
    x=1

    def __init__(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
        obj.name = x
        obj.age = y
        obj.sex = z

    def run(self):
        print('----->', self)

obj1=People('egon',18,'male') #People.__init__(obj1,'egon',18,'male')
obj2=People('lxx',38,'female') #People.__init__(obj2,'lxx',38,'female')
obj3=People('alex',38,'female') #People.__init__(obj3,'alex',38,'female')


# __init__方法
# 强调:
#   1、该方法内可以有任意的python代码
#   2、一定不能有返回值
class People:
    country='China'
    x=1

    def __init__(obj, name, age, sex): #obj=obj1,x='egon',y=18,z='male'
        # if type(name) is not str:
        #     raise TypeError('名字必须是字符串类型')
        obj.name = name
        obj.age = age
        obj.sex = sex


    def run(self):
        print('----->', self)


# obj1=People('egon',18,'male')
obj1=People(3537,18,'male')

# print(obj1.run)
# obj1.run() #People.run(obj1)
# print(People.run)
复制代码

三、类的定义

"""

"""


def choose_course(stu_dic, course):
    """

    stu_dic = {
        'name': 'egon',
        'age': 18,
        'gender': 'male',
        'courses': []
    }
    :param stu_dic:
    :param course:
    :return:
    """
    stu_dic['courses'].append(course)
    print("%s选课成功 %s" % (stu_dic['name'], stu_dic['courses']))


# Student = {
#     'school': 'SH',
#     'choose_course': choose_course
# }
# stu1 = {
#     'name': 'egon',
#     'age': 18,
#     'gender': 'male',
#     'courses': [],
#
# }
#
# stu2 = {
#     'name': 'ly',
#     'age': 18,
#     'gender': 'male',
#     'courses': [],
# }

# stu1['choose_course'](stu1, 'python')


"""
    定义类了,用专业的语法
    
    1. 定义类
    class 类名():
        pass
        
    2. 函数的定义
        def 函数名():
            pass
"""


# 定义类
class Student():
    # 定义属性
    school = 'SH'

    def choose_course(stu_dic, course):
        """
        stu_dic = {
            'name': 'egon',
            'age': 18,
            'gender': 'male',
            'courses': []
        }
        :param stu_dic:
        :param course:
        :return:
        """

        stu_dic['courses'].append(course)
        print("%s选课成功 %s" % (stu_dic['name'], stu_dic['courses']))
    # print("12222222")

"""
定义类发生了什么事?
    1. 立即执行类体代码
    2. 产生一个类的名称空间, 把类中的名字扔到字典里面去
    3. 把类的名称空间绑定给__dict__,  类名.__dict__
"""
# 查看类的名称空间
print(Student.__dict__)

# 调用类产生对象
stu1 = Student()
stu2 = Student()
stu3 = Student()

print(stu1.__dict__)

 四、定义对象独有的属性

# 定义类
# class Student():
#     # 定义属性
#     school = 'SH'
#
#     def choose_course(stu_dic, course):
#         """
#         stu_dic = {
#             'name': 'egon',
#             'age': 18,
#             'gender': 'male',
#             'courses': []
#         }
#         :param stu_dic:
#         :param course:
#         :return:
#         """
#         stu_dic['courses'].append(course)
#         print("%s选课成功 %s" % (stu_dic['name'], stu_dic['courses']))
#     # print("12222222")
#
#
# stu1 = Student()
# stu2 = Student()
# stu3 = Student()
#
# # stu1.__dict__ => {}
# # 版本1:
# stu1.name = 'egon'       # stu1.__dict__['name'] = 'egon'
# stu1.age = 18            # stu1.__dict__['age'] = 18
# stu1.gender = 'male'     # stu1.__dict__['gender'] = 'male'
#
# stu2.name = 'egon'       # stu1.__dict__['name'] = 'egon'
# stu2.age = 18            # stu1.__dict__['age'] = 18
# stu2.gender = 'male'     # stu1.__dict__['gender'] = 'male'
#
# stu3.name = 'jason'       # stu1.__dict__['name'] = 'egon'
# stu3.age = 18            # stu1.__dict__['age'] = 18
# stu3.gender = 'male'     # stu1.__dict__['gender'] = 'male'

# stu2.__dict__['name'] = 'ly'
# stu2.__dict__['age'] = 18
# stu2.__dict__['gender'] = 'male'

"""
stu1 = {'name': 'egon', 'age': 18, 'gender': 'male'}
"""

# print(stu1.__dict__)
# print(stu2.__dict__)

"""
stu1 = {
    'username':"egon"
}
"""


# stu1.__dict__ => {}
# 版本2:
# stu1.name = 'egon'       # stu1.__dict__['name'] = 'egon'
# stu1.age = 18            # stu1.__dict__['age'] = 18
# stu1.gender = 'male'     # stu1.__dict__['gender'] = 'male'
#
# stu2.name = 'egon'       # stu1.__dict__['name'] = 'egon'
# stu2.age = 18            # stu1.__dict__['age'] = 18
# stu2.gender = 'male'     # stu1.__dict__['gender'] = 'male'
#
# stu3.name = 'jason'       # stu1.__dict__['name'] = 'egon'
# stu3.age = 18            # stu1.__dict__['age'] = 18
# stu3.gender = 'male'     # stu1.__dict__['gender'] = 'male'

# def init(stu_obj, name, age, gender):
# #     stu_obj.name = name  # stu1.__dict__['name'] = 'egon'
# #     stu_obj.age = age,  # stu1.__dict__['age'] = 18
# #     stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'
# #
# # init(stu1, 'egon1', 18, 'male')
# # init(stu2, 'egon2', 18, 'male')
# # init(stu3, 'egon3', 18, 'male')
# #
# # print(stu1.__dict__)
# # print(stu2.__dict__)
# # print(stu3.__dict__)

# 版本3

class Student():
    # 定义属性
    school = 'SH'

    # 当调用类的时候,会自动调用的函数, 初始化方法 (********)
    # def __init__(stu_obj, name, age, gender):
    #     # stu_obj   => stu1
    #     stu_obj.name = name  # stu1.__dict__['name'] = 'egon'
    #     stu_obj.age = age,  # stu1.__dict__['age'] = 18
    #     stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'

    def choose_course(stu_dic, course):
        stu_dic['courses'].append(course)
        print("%s选课成功 %s" % (stu_dic['name'], stu_dic['courses']))


# 调用类
"""
    调用类发生什么事?
       1. 会自定触发__init__方法 
       2. 把对象本身当成第一个参数自动传递给了__init__方法
"""
# stu1 = Student('egon', 18, 'male')  # Student(stu1, 'egon', 18, 'male')
# stu2 = Student('egon1', 18, 'male')  # Student(stu2, 'egon', 18, 'male')
# stu2 = Student()
# stu3 = Student()

stu2 = Student()
stu1 = Student()



# def init(stu_obj, name, age, gender):
#     stu_obj.name = name  # stu1.__dict__['name'] = 'egon'
#     stu_obj.age = age,  # stu1.__dict__['age'] = 18
#     stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'


# init(stu1, 'egon1', 18, 'male')
# init(stu2, 'egon2', 18, 'male')
# init(stu3, 'egon3', 18, 'male')

print(stu1.__dict__)
print(stu2.__dict__)
# print(stu3.__dict__)

 

 

五、属性查找

类有两种属性:数据属性和函数属性

1. 类的数据属性是所有对象共享的

2. 类的函数属性是绑定给对象用的

#类的数据属性是所有对象共享的,id都一样
print(id(OldboyStudent.school))

print(id(s1.school))
print(id(s2.school))
print(id(s3.school))

'''
4377347328
4377347328
4377347328
4377347328
'''



#类的函数属性是绑定给对象使用的,obj.method称为绑定方法,内存地址都不一样
#ps:id是python的实现机制,并不能真实反映内存地址,如果有内存地址,还是以内存地址为准
print(OldboyStudent.learn)
print(s1.learn)
print(s2.learn)
print(s3.learn)
'''
<function OldboyStudent.learn at 0x1021329d8>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x1021466d8>>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x102146710>>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x102146748>>
'''

 

class Student():
    # 定义属性
    school = 'SH'
    # country = 'Chinese'
    # 当调用类的时候,会自动调用的函数, 初始化方法 (********)
    def __init__(stu_obj, name, age, gender, courese=None):
        # stu_obj   => stu1
        if courese is None:
            courese = []
        stu_obj.name1 = name  # stu1.__dict__['name'] = 'egon'
        stu_obj.age = age,  # stu1.__dict__['age'] = 18
        stu_obj.gender = gender  # stu1.__dict__['gender'] = 'male'
        stu_obj.courese = courese  # stu1.__dict__['gender'] = 'male'

    def choose_course(stu_obj, course):
        # stu_obj => stu
        # stu_dic['courses'].append(course)
        stu_obj.courese.append(course)

        """
        stu_obj = {'name': 'egon', 'age': (18,), 'gender': 'male', 'courese': []}
        """
        print("%s选课成功 %s" % (stu_obj.name, stu_obj.courese))


stu = Student('egon', 18, 'male')
stu1 = Student('egon1', 18, 'male')

# print(stu.__dict__)
# 类属性的查找
# print(Student.__dict__['school'])

#
# print(Student.school)

# 增加
# Student.country = 'Chinese'


# 修改
# Student.school = 'BJ'

# 删除
# del  Student.school
# Student.choose_course(stu, 'python')
# Student.choose_course(stu1, 'linux')
# print(Student.choose_course)


# print(Student.__dict__)

# 对象的属性查找
# print(stu.__dict__)
# print(stu.name)
# print(stu.age)
# print(stu.gender)
#
# stu.name = 'xxx'
# print(stu.name)
# print(stu.__dict__)
# stu.school = 'xxxxxxx'
# print(stu.__dict__)
# print(stu.school)

# 类中的方法类可以调用,但是推荐对象来调用,对象来调用,把对象本身当成第一个参数传递给函数的第一个参数
stu.choose_course('python') # stu.choose_course(stu, 'python')
stu1.choose_course('linux') # stu.choose_course(stu, 'python')

 

调用类的过程称之为实例化,发生了3件事:

1.先产生一个空对象

2.python会自动调用类中的__init__方法,将空对象已经调用类时括号内传入的参数一同传给__init__方法

3.返回初始完的对象

 

总结__init__方法:

1.会在调用类时自动触发执行,用来为对象初始化自己独有的数据

2.__init__方法内应该存放是为对象初始化属性的功能,但是是可以存放任意其他代码,想要在类调用时就立即执行的代码都可以放到该方法内

3.__init__方法必须返回None

 

 

 

   

posted @ 2021-08-23 17:21  甜甜de微笑  阅读(37)  评论(0编辑  收藏  举报