美文网首页
2018-10-19面向对象和pygame

2018-10-19面向对象和pygame

作者: 我是你唯一的py文件 | 来源:发表于2018-10-19 20:24 被阅读0次

    ️recode

    1.静态方法和类方法、对象方法
    对象方法:
    a.直接声明在类中
    b.自带的self参数
    c.对象来调用
    d.实现函数的功能需要用到对象的属性

    类方法:
    a.声明在@classmethod的下面
    b.自带的cls参数
    c.类来调用
    d.实现函数的功能需要使用到类(类的字段)

    静态方法:
    a.声明在@staticmethod的下面
    b.没有自带的参数
    c.类来调用
    d.实现函数的功能既不需要对象的属性也不需要类的字段

    2.属性的私有化
    在属性名或者方法名前加__

    3.对象属性的保护(添加getter和setter)

    class Person:
        def __init__(self):
            self._age = 0
    
        # 对象.属性
        @property
        def age(self):
            return self._age
    
        # 对象.属性=值
        @age.setter
        def age(self, value):
            if not 0<=value<=150:
                raise ValueError
            self._age = value
    
    
    p1 = Person()
    p1.age = 20
    print(p1.age)
    

    ️类的继承

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

    1.什么是继承

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

    2.怎么继承

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

    3.能继承哪些东西

    对象属性、对象方法、类的字段、类方法、静态方法都可以继承
    被私有化的属性或者类也能被继承但是毕竟被私有化了也没必要是用了
    注意:如果设置类slots会约束当前类的对象属性,并且会导致当前类的dict属性不存在;
    继承后,slots的值不会约束到子类的对象属性,但是会导致子类对象的dict只有在当前类中添加的属性
    slots

    class Person:
        num = 12
        __slots__ = ('name', 'age', 'sex')
    
        def __init__(self, name='x', age=18):
            self.name = name
            self.age = age
    
        def eat(self, food):
            print('%s在吃%s' % (self.name, food))
    
        @staticmethod
        def func1():
            print('Person的静态方法')
    
        @classmethod
        def show_num(cls):
            print('num=%s' % cls.num)
    
    
    class Student(Person):
        pass
    
    # 创建Student类的对象
    stu1 = Student()
    print(stu1.name)
    stu1.eat('肉')
    
    print(Student.num)
    Student.show_num()
    Student.func1()
    

    ️重写

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

    1.添加新的方法

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

    2.

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

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

    类.方法(),对象.方法()
    先看当前类是否有这个方法,如果有就直接调用当前类中相应的方法;
    如果没有就去当前类的父类中去看有没有这个方法,如果有就调用父类的这个方法;
    如果父类中也没有这个方法就去父类中的父类去找依次内推直到找到位置。
    如果找到基类object,还没有找到这个方法,程序才会异常

    class Person:
    
        def __init__(self, name):
            self.name = name
    
        def eat(self, food):
            print('%s在吃%s' % (self.name, food))
    
        @staticmethod
        def run():
            print('人在跑步')
    
        @classmethod
        def get_up(cls):
            print('洗漱')
            print('换衣服')
    
    
    class Student(Person):
    
        def syudy(self):
            print('%s在学习' % self.name)
    
        def eat(self, food):
            super().eat(food)
            print('喝一杯牛奶!')
    
        @staticmethod
        def run():
            print('学生在跑步')
    
        @classmethod
        def get_up(cls):
            # super() -> 获取当前类的的夫类
            # super().get_up() -> 调用夫类的get_up方法
            super().get_up()    # 可以保留夫类get_up的功能
            print('背书包')
    
    
    
    stu1 = Student('x')
    p1 = Person('y')
    
    stu1.syudy()
    stu1.run()
    p1.run()
    print('------')
    p1.get_up()
    p1.eat('2')
    print('=======')
    stu1.get_up()
    stu1.eat('w')
    

    ️添加属性

    1.添加字段:

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

    2.添加对象的对象属性

    子类是通过继承父类的init方法来继承父类的对象属性

    
    class Car:
        def __init__(self, color='白色'):
            self.color = color
            self.price = '10'
        num = 201
    
    
    class SportsCar(Car):
        # 添加字段
        num = 12
        wheel_count = 4
    
        def __init__(self, horsepower, color):
            # 通过super()去调用父类的init方法,用来继承父类的对象属性
            super().__init__(color)
            self.horsepower = horsepower
    
    print(Car.num)
    print(SportsCar.num, SportsCar.wheel_count)
    
    # 当子类中没有声明init方法。通过子类的构造方法创建对象的时候会自动调用父类的init方法
    sp1 = SportsCar(1,1)
    # sp1.color = 'red'
    print(sp1.__dict__)
    

    声明一个Person类,有属性名字、年龄和生份证号码。
    要求创建Person对象的时候必须给名字赋值,年龄和生份证可以赋值也可以不赋值

    声明一个学生类,有属性名字、年龄、生份证号码和学号,成绩

    >要求创建学生的时候,必须给学号赋值,可以给年龄、名字赋值,不能给生份证号和成绩赋值

    class Person:
        def __init__(self, name, age=0, num_id=''):
            self.name = name
            self.age = age
            self.num_id = num_id
    
    
    class Student(Person):
        def __init__(self, stu_id,  age=0, name='', ):
            super().__init__(name, age)
            self.stu_id = stu_id
            self.score = 0
    
    p1 = Person('h', 2)
    
    print(p1.__dict__)
    
    s1 = Student(1, name='1', age=2)
    
    print(s1.__dict__)
    

    ️运算符的重载

    运算符重载: 通过实现类相应的魔法方法,来让类的对象支持相应的运算符(+, -, > ,< 等)

    值1 运算符 值2 ---> 值1.魔法方法(值2)

    
    10 > 20   # int类,实现 > 对应的魔法方法 __gt__
    10 < 20
    ['12', 2] > ['abc', 1, 34]  # list类,实现 > 对应的魔法方法 __gt__
    
    10 / 20   # __truediv__
    
    20 % 10
    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中垃圾回收机制是用来管理堆中的内存堆释放

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

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

    系统每隔一定的时间就回去检测当前程序中所有的对象的引用计数值,如果对象引用计数是0对象对应的内存就会被销毁
    每一个对象都有引用计数属性,用来存储当前对象被引用的次数。可以通过sys模块中的getrefcount去获取一个对象的引用计数值

    from sys import getrefcount
    a = 'qw'
    b = 'qw'
    
    print(id(a), id(b))
    
    aaa = [1, 2, 3]
    print(getrefcount(aaa))  # 2
    
    # 增加引用计数:增加引用(增加保存当前对象地址的变量个数)
    a1 = ['abc']
    b1 = a1
    list1 = [a1, 1]
    print(getrefcount(a1))
    
    # 2.减少引用计数
    del b1
    print(getrefcount(a1))
    
    

    ️认识pygame

    pygame是一个用python写2D游戏的第三方库

    import pygame
    
    # 1.游戏初始化
    
    pygame.init()
    
    # 2.创建游戏窗口
    screen = pygame.display.set_mode((800, 600))
    
    # 先睡一张图片
    image = pygame.image.load('./files/tp.jpg')
    """
    窗口.blit(图片对象,坐标) --> 坐标: (x, y)
    """
    screen.blit(image, (0, 0))
    
    """
    将内容贴出来
    """
    pygame.display.flip()
    # 3.创建一个游戏循环
    flag = True
    while flag:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print('点了关闭按钮')
                flag = False
                # exit()  # 结束线程(结束线程)
    
    

    相关文章

      网友评论

          本文标题:2018-10-19面向对象和pygame

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