day16

作者: 13147abc | 来源:发表于2018-10-22 15:28 被阅读0次

    类的继承

    • python中的类支持继承,并且支持多继承()

    1.什么是继承

    • 父类(超类):被继承的类
      子类:去继承的类
      继承就是让子类直接拥有父类的属性和方法(注意:继承后父类的东西不会减少)。
      python中所有的类都是直接或者间接的继承object

    2.怎么继承

    • class 类名(父类):...
      class 类名: == class 类名(object)

    3.能继承那些东西

    • 对象属性、对象方法、类的字段、类方法、静态方法都可以继承
      注意:如果设置了slots会约束当前类的对象属性的个数,并且会导致当前类的对象的dict属性不存在;
      继承后,slots不会约束之类的对象属性但是会导致子类对象的dict只有在当前类的添加的属性
    class Person:
        __num = 61
        def __init__(self, name='小明', age=18):
            self.name = name
            self.age = age
    
        def eat(self, food:str):
            print('%s在吃%s'%(self.name,food))
    
    
    class Student(Person):
        pass
    
    stu1 = Student()
    print(stu1.name,stu1.age)
    stu1.eat('面条')
    print()
    

    重写

    • 继承后子类会拥有父类的属性和方法,也可添加自己的属性和方法

    1.添加新的方法

    • 直接在子类中声明新的方法,新的方法只能通过子类来使用

    2.重写

    a.子类继承父类的方法,在子类中去重新实现这个方法的功能 --完全重写
    b.在子类方法中通过super().父类方法去保留父类对应的方法的功能

    3.类中的函数的调用过程

    • 类.方法(),对象.方法()

    • 先看当前类是否有这个方法,如果有就直接调用当前类中的相应方法:如果没有就去当前类的父类中看看有没有这个方法,如果父类中也没有这个方法 就去父类的父类中找,以此类推知道找到为止。如果找到基类object,还没有找到这个方法,程序才会崩溃

    class Person:
        def __init__(self, name='sss'):
            self.name = name
        def eat(self, food):
            print('%s在吃%s' %(self.name, food))
    
        @staticmethod
        def run():
            print('人在跑步')
    
        @classmethod
        def get_up(self):
            print('==============')
            print('换衣服')
    
    
    
    class Student(Person):
        def study(self):
            print('%s在学习' %self.name)
    
        def eat(self, food):
            print('对象方法:',super())
    
    
        @staticmethod
        def run():
            print('学生在跑步')
    
        @classmethod
        def get_up(cls):
            #super() -> 获取当前类的父类
            #super().get_up() ->调用父类的get_up方法
            super().get_up()
            print('背书包')
    
    stu1 = Student()
    stu1.study()
    stu1.run()
    stu1.get_up()
    

    添加属性

    1.添加字段:

    • 就直接在子类声明新的字段

    2.添加对象属性

    • 子类是通过继承父类的init方法来继承的父类的对象属性
    class Car:
        def __init__(self, color):
            print('Car:',self)
            # self = Car对象, color = '黑色'
            self.color = color
            self.price = 10
    
        num = 10
    
    
    class SportsCar(Car):
        # 修改字段的默认值
        num = 8
        # 添加字段
        wheel_count = 4
    
        # 给子类添加新的对象属性
        def __init__(self, horsepower,color):
            print('SpCar:',self)
            # self = sp1, horsepower = 100, color='黑色'
            # 通过super()去调用父类的init方法,用来继承父类的对象属性
            super().__init__(color)  # Car对象.__init__('黑色')
            self.horsepower = horsepower  # self.horsepower = 100
    
    print(Car.num)
    SportsCar.num = 19
    print(SportsCar.num, SportsCar.wheel_count)
    
    # 当子类没有中没有声明init方法,通过子类的构造方法创建对象的时候会自动调用父类的init方法。
    sp1 = SportsCar(100, '黑色')
    print(sp1.color)
    
    print(sp1)
    
    # 练习:
    # 声明一个Person类,有属性名字、年龄和身份证号码。
    # 要求创建Person的对象的时候,必须给名字赋值,年龄和省份证可以赋值也可以不赋
    # Person('小明')
    # Person('xiaoming', 18)
    # Perosn('小红', 18, '28283983')
    
    # 声明一个学生类,有属性名字、年龄、身份证号码和学号,成绩(用继承)
    # 要求创建学生的时候,必须给学号赋值,可以给年龄,名字赋值,不能给省份证号,和成绩赋值
    # Student('stu001', 18, 'mingzi')
    # Student('stu001', 18)
    # Student('stu001', name='mingzi')
    class Person:
        def __init__(self, name, age=0, id=''):
            self.name = name
            self.age = age
            self.id = id
    
    # p2 = Person() # TypeError: __init__() missing 1 required positional argument: 'name'
    p1 = Person('小明')
    p2 = Person('小红', 10, '344')
    
    class Student(Person):
        def __init__(self, study_id, age=0, name=''):
            super().__init__(name, age)
            self.study_id = study_id
            self.score = 0
    
    stu1 = Student('001')
    

    运算符的重载

    • 运算符重载:通过实现类响应的魔法,来让类的对象支持相应的运算符(+, -, > ,< 等)
      值1 运算符 值2 ---> 值1.魔法方法(值2)
    import copy
    import random
    
    class Student:
        def __init__(self, name, age, score):
            self.name = name
            self.age = age
            self.score = score
    
        #  __gt__就是 > 对应的魔法方法
        def __gt__(self, other):
            # self -> 指的是大于符号前面的值, other -> 指的是>符号后面的值
            return self.score > other.score
    
        # __lt__是 < 对应的魔法方法
        # 注意:gt和lt只需要实现一个就可以了
        def __lt__(self, other):
            return self.score < other.score
    
        def __add__(self, other):
            return self.score + other.score
    
        def __mul__(self, other: int):
            result = []
            for _ in range(other):
                result.append(copy.copy(self))
            return result
    
    
    stu1 = Student('小哈', 23, 89)
    stu2 = Student('小🌺', 19, 90)
    print(stu1 > stu2)
    print(stu1 < stu2)
    
    print(stu1 + stu2)
    
    students = stu1*10
    print(students)
    students[0].name = '小明'
    
    
    class Person:
        def __init__(self, name='张三', age=0):
            self.name = name
            self.age = age
    
        def __mul__(self, other: int):
            result = []
            for _ in range(other):
                result.append(copy.copy(self))
            return result
    
        def __gt__(self, other):
            return self.age > other.age
    
    
        # 定制打印格式
        def __repr__(self):
            return str(self.__dict__)[1:-1]
    
    
    # 同时创建10个人的对象
    persons = Person()*10
    # persons = 10 * Person()
    # print(persons)
    
    for p in persons:
        p.age = random.randint(15, 35)
    
    print(persons)
    
    # 列表元素是类的对象,使用sort对列进行排序
    persons.sort()
    print(persons)
    
    print(max(persons))
    
    
    class Dog:
        def __mul__(self, other):
            pass
    
    dog1 = Dog()
    dog1 * 4
    # 4 * dog1  # 实现不了
    

    内存管理机制

    • python中的内存管理 --》自动管理 --》垃圾回收机制
      内存结构中分栈区间,栈区间中内存是系统自动开启自动释放,堆区间的内存需要手动申请手动释放。
      但是目前绝大部分编程语言,都提供了一套属于自己的关于堆中的内存管理方案
      --》python中垃圾回收机制是用来管理堆中的内存的释放

    1.内存的开辟

    • python中将值赋给变量的是,会先在堆中开辟空间将数据存起来,然后再数据对应的地址返回给变量,存在栈中。但是如果数据是数字或字符串,会现在缓存区中查看这个数据之前是否已经创建过,如果没有就去创建空间存数据,然后将地址返回。如果之前已经创建过就直接将之前的地址返回

    2.内存的释放 --》垃圾回收机制

    • 系统每隔一段时间会检测当前程序中所有的对象的引用计数值是否为0;如果对象的引用计数是0对象对应的内存就会被销毁,如果不是0就不销毁

    3.引用计数

    每一个对象都有引用计数属性,用来存储当前对象被引用的次数,可以通过sys模块中的getrefcount获取一个对象的引用值

    from sys import getrefcount
    
    c = [1, 2]
    d = [1, 2]
    print(id(c), id(d))
    
    a = 100
    b = 100
    print(id(a), id(b))
    
    s1 = 'abc'
    s2 = 'abc'
    print(id(s1), id(s2))
    
    aaa = [1, 2, 3]
    print(getrefcount(aaa))
    aaa1 = [1, 2, 3]
    aaa2 = [1, 2, 3]
    aaa3 = [1, 2, 3]
    print(getrefcount(aaa))
    
    
    bbb = 10
    print(getrefcount(bbb))
    ccc = 10
    ddd = 10
    print(getrefcount(bbb))
    
    # 1.增加引用计数:增加引用(增加保存当前对象地址的变量的个数)
    a1 = ['abc']
    b1 = a1
    list1 = [a1, 100]
    print(getrefcount(a1))
    
    # 2.减少引用计数
    del b1   # 删除存储对象地址的变量
    print(getrefcount(a1))
    
    list1[0] = 10   # 修改存储对象地址变量的值
    print(getrefcount(a1))
    
    a1 = 100
    

    相关文章

      网友评论

          本文标题:day16

          本文链接:https://www.haomeiwen.com/subject/wjrgzftx.html