• 面向对象


    面向对象

    一、面向对象和面向过程的优缺点

    面向过程 面向对象
    优点 复杂问题流程化,进而简单化 可扩展性高
    缺点 可扩展性差 编写复杂

    二、类与对象

    2.1 定义类

    一系列共同的属性和方法。eg:人类

    class 关键字 类名:
        pass
    

    假设我们要定义学生这样一个类,将下面一段代码中一系列共同的属性和方法提取出来写成代码。

    '''
    学生1:
        学校:老男孩
        姓名:李铁蛋
        性别:男
        年龄:18
        方法:
            选课
            学习
    学生1:
        学校:老男孩
        姓名:jiayi
        性别:女
        年龄:20
        方法:
            选课
            学习
    '''
    ---------------------------------------------------------------
    class Student:
        school = 'oldboy'  #属性
        def choose(self):
            print("这是一个选课的方法")
        def sutdy(self):
            print("这是一个学习的方法")
    

    2.2 类

    2.2.1获取类的属性和方法

    类.__dict__
    
    #定义一个学生类
    class Student:
        school = 'oldboy'  #属性
        def choose(self):
            print("这是一个选课的方法")
        def sutdy(self):
            print("这是一个学习的方法")
    print(Student.__dict__)
    -----------------------------------------------------------------------------------
    {'__module__': '__main__', 'school': 'oldboy', '__init__': <function Student.__init__ at 0x000001BBBC6E1620>, 'choose': <function Student.choose at 0x000001BBC3912C80>, 'study': <function Student.study at 0x000001BBC3912D08>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
    

    2.2.2类来调用属性和方法
    -通过dict来调用(复杂,不用)

    print(Student.__dict__)    #获取到的是一个字典
    print(Student.__dict__['school'])  #获取到的是学校这个属性
    print(Student.__dict__['choose'])   # 获取到的是一个函数地址,因为没有传参
    Student.__dict__['choose'](123)   #调用了choose函数
    ---------------------------------------------------------------
    {'__module__': '__main__', 'school': 'oldboy', 'choose': <function Student.choose at 0x0000017A47001620>, 'sutdy': <function Student.sutdy at 0x0000017A4E213C80>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
    oldboy
    <function Student.choose at 0x0000017A47001620>
    这是一个选课的方法   
    
    

    ​ -类来调用属性和方法 (类名.属性/函数)

    print(Student.school)
    Student.choose(123)  #函数一定要传参
    -----------------------------------------------------------
    oldboy
    这是一个选课的方法
    

    2.3产生对象

    类加括号,生成对象

    对象 = 类名()
    
    stu1=Student()  #学生1就是一个对象
    

    2.4对象

    2.4.1对象获取属性和方法

    对象.__dict__
    
    stu1=Student()  #产生对象
    print(stu1.__dict__)    #此处为空字典是因为他没有是有的属性,还没有定义属性,所以是空字典
    -----------------------------------------------------
    {}
    

    2.4.2对象调用属性和方法

    # 对象.属性/函数 
    stu1=Student()
    print(stu1.school)
    stu2=Student()
    print(stu2.school)
    -------------------------------------------------------------
    oldboy
    oldboy
    

    2.5 对象自己的属性和方法

    stu1=Student()
    stu1.name='jiayi'   #对象自己定义的属性,也就是对象赋属性
    stu1.school='xxxx'    #对象自己定义的属性,也就是对象赋属性
    print(stu1.name)
    print(stu1.school)
    print(stu1.__dict__)   #此时查看就不会为空字典
    ---------------------------------------------------
    jiayi
    xxxx
    {'name': 'jiayi', 'school': 'xxxx'}
    

    三、对象的绑定方法

    3.1 属性查找顺序

    先从对象自身找------>类中找----->报错

    3.2 对象赋属性

    • 方式一:
    stu1 = Student()
    stu1.name = 'jiayi'
    
    • 方式二(通过__init__):
      -在类中定义该方法,方法上写一些参数
      -在对象实例化产生对象时,在括号中传的值,会被传到__init__中
    #定义类
    class Student:
        school = 'oldboy'  #变量表示属性
        # __init__ 看好名字,不是__int__
        def __init__(self,name):
            self.name=name
        def choose(self):
            print("这是一个选课的方法")
        def sutdy(self):
            print("这是一个学习的方法")
            
    #产生对象
    stu1=Student('jiayi')
    #内部帮我们做了一些事:当我在实例化产生对象的时候,会自动调用__init__方法,完成对象的初始化
    print(stu1.name)
    stu2=Student('ypp')
    print(stu2.name)
    -----------------------------------------------------------
    jiayi
    ypp
    

    3.3 绑定方法

    -定义在类内部的方法:

    -类来调用:就是一个普通函数,有几个参数就需要传几个参数

    -对象来调用:它叫对象的绑定方法,第一个参数不需要传,自动传递

     #定义类
    class Student:
        school = 'oldboy'  #变量表示属性
        # __init__ 看好名字,不是__int__
        def __init__(self,name):
            self.name=name
        def choose(self):
            print("这是一个选课的方法")
        def sutdy(self):
            print("这是一个学习的方法")
    
            
    stu1=Student('李铁蛋')
    stu1.study()
    -------------------------------
    李铁蛋
    

    3.4 一切皆对象

    python中,字典,列表字符串....都是对象

    类即类型 eg:字典类

    #类实例化产生对象
    ll=list([1,2,3])
    #对象调用对象的绑定方法,修改对象自己
    ll.append(5)
    print(ll)
    print(type(ll))
    --------------------------------------------------------------
    [1, 2, 3, 5]
    <class 'list'>
    

    四、人狗大战小游戏

    #定义两个类,人和狗
    #人和狗的共同属性  1.姓名2.攻击力3.生命值
    #人和狗的方法     咬这个动作,可以定义为一个函数
    
    #定义一个狗类
    class Dog:
        type_dog = '藏獒'
        def __init__(self,name,atk,hp):
            self.name = name
            self.atk = atk
            self.hp = hp
    
        def fight(self,target):
            target.hp -= self.atk  #攻击目标的生命值等于攻击目标原本的生命值减去攻击者的攻击力
    
            print(f"{self.type_dog}狗{self.name},攻击了{target.name},掉血{self.atk},血量剩余为{target.hp}")
    
    #定义一个人类
    class Human:
        type_dog = '男'
    
        def __init__(self, name, atk, hp):
            self.name = name
            self.atk = atk
            self.hp = hp
    
        def fight(self, target):
            target.hp -= self.atk
    
            print(f"{self.type_dog}人{self.name},攻击了{target.name},掉血{self.atk},血量剩余为{target.hp}")
            
    #产生对象
    Hum1 = Human('ypp',50,100)
    Dog1 = Dog('毛毛',20,500)
    
    #对象调用方法
    Hum1.fight(Dog1)
    Dog1.fight(Hum1)
    Hum1.fight(Dog1)
    Dog1.fight(Hum1)
    ----------------------------------------------------------------------------------------
    男人ypp,攻击了毛毛,掉血50,血量剩余为450
    藏獒狗毛毛,攻击了ypp,掉血20,血量剩余为80
    男人ypp,攻击了毛毛,掉血50,血量剩余为400
    藏獒狗毛毛,攻击了ypp,掉血20,血量剩余为60
    
  • 相关阅读:
    06-继承与多态(动手动脑与验证)
    课堂测试四(文件读写)
    字符串加密
    String方法阅读笔记
    03-类与对象(动手动脑)
    计算已经创建了多少个对象
    递归练习(课程作业)
    02-方法(动手动脑)
    猜数字游戏
    JAVA语言实现简单登录界面
  • 原文地址:https://www.cnblogs.com/yanjiayi098-001/p/11413410.html
Copyright © 2020-2023  润新知