函数面向对象编程及文件的读取

函数

'''

名字

参数/默认值/可变参数-可变参数允许传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个元组

命名关键字参数-关键字参数允许传入0个或任意个含参数名的参数,这些关键字参数在函数的内部自动组装成为一个字典。

返回值

嵌套定义

高阶函数-Lambda函数(匿名函数)/闭包/偏函数/柯里化

Lambda 函数例子:

def calc(num_list, func):
    total = num_list[0]
    for index in range(1, len(num_list))
        total = func(total, num_list[index])
    return total

def main():
    my_list = [1,2,3,4,5]
    print(calc(my list, lambda x, y: x + y))

标识符

print(a)

LEGB-not defined-global/nonlocal

'''

类和对象

'''

单一职责原则

开闭原则

依赖倒转原则

里氏替换原则

接口隔离原则

合成聚合复用原则

迪米特法则(最少知识原则)

在python中,所有数据类型都可以视为对象,当然也可以自定义对象,自定义对象数据类型就是面向对象中的类(class)的概念,把具有相同属性和方法的对象归为一个类。类是对象的模版或蓝图,是对秀爹抽象化,对象是类的实例化。类不代表具体的事物,而对象表示具体的事物。class后面紧接着类名,即 Myclass,类名通常是大写开头的单词,紧接着是object,表示该类是从哪个类继承下来的,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。类 Myclass中只有一个方法 infor,类的方法至少有一个参数self,self代表将来要创建的对象本身。

当 class 语句执行时,则知识赋值给对象的变量,而对象可以用任何普通表达式引用。就像其它事物一样,类名总是存在于模块中,单一模块文件可以有一个以上的类,class语句会在导入时执行已定义的变量名,而这些变量名会变成独立的模块属性。更通用的情况时,每个模块可以混合任意数量的变量、函数以及类,而模块内的所有变量名的行为都相同。

类的方法

在python中,类有3种方法--实例方法,类方法和静态方法。实例方法一般由被类所生成的实例所调用,唯一需要注意的是在定义实例方法的时候,和其它面向对象语言的实例方法使用的时候差不多,实例方法内部逻辑是否需要使用参数,形参列表第一个参数都要定义且最好命名为self,形参列表的第一个参数self代表的是实例化的类对象的引用。

静态方法其实就是类中的一个普通函,它并没有默认传递的参数,在创建静态方法的时候,需要用到内置函数:staticmethod(),要在类中使用静态方法,需在类成员函数签名加上@staticmethod标记符,以表示厦门的成员函数是静态函数。使用静态方法的好处是,不需要定义实例即可使用这个方法,另外,多个实例共享此静态方法。类方法其实和实例方法类似,不过其第一个参数一般是cls而不是self,一个类方法就是可以通过类或者它的实例来调用的方法,不管是用类来调用这个方法还是类实例调用这个方法,该方法的第一个参数总是定义该方法的类对象。

__str__会返回字符串表达形式。

__slots__ 当我们创建一个类而没有使用__slot__属性时,python会隐含地为每一个实例创建一个名为__dict__的私有字典,该字典存放着每个实例的数据属性,这是我们能够向对象中增加属性或从中移除属性的原因。如果对于某个对象,我们只需要访问其原始属性,而不需要增加或移除属性,那么可以创建不包含私有字典__dict__的类。这可以定义一个名为__slots__的类属性来实现,其值是个包含类中属性名的元组,这样的类不能添加或移除属性。

继承

继承是为代码重用而设计的,当我们设计一个新类时,为了代码重用可以继承一个已涉及好的类。在继承关系中,原来设计好的类称为父类,新设计的类称为子类。继承允许基于类的特点创建另一个类,完成这个步骤需要两个步骤。首先,在类上增加关联,类似于实例和类之间的关联。其次,这种关联关系能够‘继承’位于关系方案上层的类的属性。通过这些属性,可以实现代码共享。子类继承父类时用class子类名(父类名)来表示,子类能继承父类的所有公有成员,在需要的时候,在子类中可通过super() 来调用父类的构造函数,也可通过父类名来调用父类的构造函数。

抽象基类

抽象基类(Abstract Base Class)也是一个类,但这个类不能用于创建对象,使用抽象基类的目的是为了定义接口(interface),抽象基类会列出一些方法与特性,而继承自抽象基类的类必须对其进行实现。这是种很有用的机制,因为我们可以将抽象基类当作一种保证,确保任何自抽象基类衍生而来的类均会实现抽象基类指定的方法与特性。所有抽象基类必须包含元类(Metaclass)abc.ABCMeta(来自abc模块),或来自其某个子类。抽象基类把基类中的方法声明为抽象(Abstract)后,再在某个具体的子类实现。

'''

文件的读取

'''

文件的写入:write(str):将字符串str写入文件

writelines(sequence_of_strings):写多行到文件,其中sequence_of_strings是由字符串所组成的列表,或者迭代器。当调用write函数的时候,write函数被python解释器所解释,然后系统调用就会调用写函数,将数据写入内核中,内核中有一个缓冲机制,数据储存在缓冲文件中。当调用close()将文件关闭的时候,会进行系统调用,内核会将缓冲区中的数据写到磁盘上。所以这就可能导致了一个问题,即写的内容和磁盘内容不一致,一般采用主动调用close()或者flush方法,写缓冲同步到磁盘或者采用写入数据大于或者等于写缓存,写缓存会自动同步到磁盘。

文件的读取

文件写入后,如果想读取出来,可以用read([size]):读取文件,readline([size]):读取一行,readlines([size]):读取完文件

'''

import requests
import json

def main():


    # response
    resp = requests.get('http://api.tianapi.com/meinv/?key=key&num=10')
    mydict = json.loads(resp.text)    # content 拿二进制数据,text文本数据
    for tempdict in mydict['newslist']:   # newslist 是mydic里面的key
        pic_url = tempdict['picUrl']
        # print(tempdict['picUrl'])
        resp = requests.get(tempdict['picUrl'])
        filename = pic_url[pic_url.rfind('/') + 1:]
        try:
            with open(filename, 'wb') as fs:
                fs.write(resp.content)
        except IOError as e:
            print(e)


if __name__ == '__main__':
    main()

pygame做的简单游戏

贪吃蛇

  1 from abc import ABCMeta, abstractmethod
  2 from random import randint
  3 
  4 import pygame
  5 
  6 BLACK_COLOR = (0, 0, 0)
  7 GREEN_COLOR = (0, 255, 0)
  8 FOOD_COLOR = (230, 185, 185)
  9 
 10 UP = 0
 11 RIGHT = 1
 12 DOWN = 2
 13 LEFT = 3
 14 
 15 
 16 class GameObject(object, metaclass=ABCMeta):
 17 
 18     def __init__(self, x=0, y=0, color=BLACK_COLOR):
 19         self._x = x
 20         self._y = y
 21         self._color = color
 22 
 23     @property
 24     def x(self):
 25         return self._x
 26 
 27     @property
 28     def y(self):
 29         return self._y
 30 
 31     @abstractmethod
 32     def draw(self, screen):
 33         pass
 34 
 35 
 36 class Wall(GameObject):
 37 
 38     def __init__(self, x, y, width, height, color=BLACK_COLOR):
 39         super().__init__(x, y, color)
 40         self._width = width
 41         self._height = height
 42 
 43     @property
 44     def width(self):
 45         return self._width
 46 
 47     @property
 48     def height(self):
 49         return self._height
 50 
 51     def draw(self, screen):
 52         pygame.draw.rect(screen, self._color,
 53                          (self._x, self._y, self._width, self._height), 4)
 54 
 55 
 56 class Food(GameObject):
 57 
 58     def __init__(self, x, y, size, color=FOOD_COLOR):
 59         super().__init__(x, y, color)
 60         self._size = size
 61         self._hidden = False
 62 
 63     def draw(self, screen):
 64         if not self._hidden:
 65             pygame.draw.circle(screen, self._color,
 66                                (self._x + self._size // 2, self._y + self._size // 2),
 67                                self._size // 2, 0)
 68         self._hidden = not self._hidden
 69 
 70 
 71 class SnakeNode(GameObject):
 72 
 73     def __init__(self, x, y, size, color=GREEN_COLOR):
 74         super().__init__(x, y, color)
 75         self._size = size
 76 
 77     @property
 78     def size(self):
 79         return self._size
 80 
 81     def draw(self, screen):
 82         pygame.draw.rect(screen, self._color,
 83                          (self._x, self._y, self._size, self._size), 0)
 84         pygame.draw.rect(screen, BLACK_COLOR,
 85                          (self._x, self._y, self._size, self._size), 1)
 86 
 87 
 88 class Snake(GameObject):
 89 
 90     def __init__(self):
 91         super().__init__()
 92         self._dir = LEFT
 93         self._nodes = []
 94         self._alive = True
 95         for index in range(5):
 96             node = SnakeNode(290 + index * 20, 290, 20)
 97             self._nodes.append(node)
 98 
 99     @property
100     def dir(self):
101         return self._dir
102 
103     @property
104     def alive(self):
105         return self._alive
106 
107     @property
108     def head(self):
109         return self._nodes[0]
110 
111     def change_dir(self, new_dir):
112         if (self._dir + new_dir) % 2 != 0:
113             self._dir = new_dir
114 
115     def move(self):
116         if self._alive:
117             snake_dir = self._dir
118             x, y, size = self.head.x, self.head.y, self.head.size
119             if snake_dir == UP:
120                 y -= size
121             elif snake_dir == RIGHT:
122                 x += size
123             elif snake_dir == DOWN:
124                 y += size
125             else:
126                 x -= size
127             new_head = SnakeNode(x, y, size)
128             self._nodes.insert(0, new_head)
129             self._nodes.pop()
130 
131     def collide(self, wall):
132         """
133         撞墙
134 
135         :param wall: 围墙
136         """
137         head = self.head
138         if head.x < wall.x or head.x + head.size > wall.x + wall.width 
139                 or head.y < wall.y or head.y + head.size > wall.y + wall.height:
140             self._alive = False
141 
142     def eat_food(self, food):
143         if self.head.x == food.x and self.head.y == food.y:
144             tail = self._nodes[-1]
145             self._nodes.append(tail)
146             return True
147         return False
148 
149     def eat_me(self):
150         pass
151 
152     def draw(self, screen):
153         for node in self._nodes:
154             node.draw(screen)
155 
156 
157 def main():
158 
159     def refresh():
160         """刷新游戏窗口"""
161         screen.fill((242, 242, 242))
162         wall.draw(screen)
163         food.draw(screen)
164         snake.draw(screen)
165         pygame.display.flip()
166 
167     def handle_key_event(key_event):
168         """处理按键事件"""
169         key = key_event.key
170         if key == pygame.K_F2:
171             reset_game()
172         else:
173             if snake.alive:
174                 new_dir = snake.dir
175                 if key == pygame.K_w:
176                     new_dir = UP
177                 elif key == pygame.K_d:
178                     new_dir = RIGHT
179                 elif key == pygame.K_s:
180                     new_dir = DOWN
181                 elif key == pygame.K_a:
182                     new_dir = LEFT
183                 if new_dir != snake.dir:
184                     snake.change_dir(new_dir)
185 
186     def create_food():
187         row = randint(0, 29)
188         col = randint(0, 29)
189         return Food(10 + 20 * col, 10 + 20 * row, 20)
190 
191     def reset_game():
192         nonlocal food, snake
193         food = create_food()
194         snake = Snake()
195 
196     wall = Wall(10, 10, 600, 600)
197     food = create_food()
198     snake = Snake()
199     pygame.init()
200     screen = pygame.display.set_mode((620, 620))
201     pygame.display.set_caption('贪吃蛇')
202     screen.fill((242, 242, 242))
203     pygame.display.flip()
204     clock = pygame.time.Clock()
205     running = True
206     while running:
207         for event in pygame.event.get():
208             if event.type == pygame.QUIT:
209                 running = False
210             elif event.type == pygame.KEYDOWN:
211                 handle_key_event(event)
212         if snake.alive:
213             refresh()
214         clock.tick(10)
215         if snake.alive:
216             snake.move()
217             snake.collide(wall)
218             if snake.eat_food(food):
219                 food = create_food()
220 
221     pygame.quit()
222 
223 
224 if __name__ == '__main__':
225     main()

大球吃小球,鼠标放置球

  1 class Ball(object):
  2 
  3     def __init__(self, center, color, radius, sx, sy):   # sx, sy 为水平移动
  4         self._center = center
  5         self.__color = color
  6         self._radius = radius
  7         self._sx = sx
  8         self._sy = sy
  9 
 10     @property
 11     def center(self):
 12         return self._center
 13 
 14     @center.setter
 15     def center(self, center):
 16         self._center = center
 17 
 18     @property
 19     def radius(self):
 20         return self._radius
 21 
 22     @radius.setter
 23     def radius(self, radius):
 24         self._radius = radius
 25 
 26     def move(self):                                        # 移动抽象
 27         '''
 28         移动小球
 29         :return:坐标
 30         '''
 31         x, y = self._center[0], self._center[1]
 32         x += self._sx
 33         y += self._sy
 34         self._center = (x, y)
 35 
 36         if x + self._radius >= 800 or x - self._radius <= 0:
 37             self._sx = -self._sx
 38 
 39         if y + self._radius >= 600 or y - self._radius <= 0:
 40             self._sy = -self._sy
 41 
 42     def eat(self, other):
 43         x, y = self._center[0], self._center[1]
 44         x += self._sx
 45         y += self._sy
 46         self._center = (x, y)
 47         is_eat = True
 48 
 49         a = (self._center[0] - other.center[0])
 50         b = (self._center[1] - other.center[1])
 51         if sqrt((a - b) ** 2) <= self._radius + other.radius:
 52             self._radius += 1
 53             other.radius == 0
 54             return is_eat
 55 
 56     def draw(self, screen):
 57         pygame.draw.circle(screen, self.__color, self._center, self._radius, 0)
 58 
 59 
 60 def random_color():
 61     red = randint(0, 255)
 62     green = randint(0, 255)
 63     blue = randint(0, 255)
 64     return red, green, blue
 65 
 66 
 67 def refresh(screen, balls):
 68     bg_color = (182, 196, 168)
 69     screen.fill(bg_color)
 70     for ball in balls:
 71         ball.draw(screen)
 72     pygame.display.flip()
 73 
 74 
 75 def main():
 76     pygame.init()
 77     screen = pygame.display.set_mode((800, 600))
 78     balls = []
 79     pygame.display.set_caption('大球吃小球')
 80     clock = pygame.time.Clock()
 81     running = True                       # 打开窗口,避免弹出
 82     while running:                          # 事件处理,比如鼠标之类的
 83         for event in pygame.event.get():    # 取出所有事件
 84             if event.type == pygame.QUIT:
 85                 running = False
 86             elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
 87                 color = random_color()
 88                 radius = randint(10, 30)
 89                 sx, sy = randint(-10, 10), randint(-10, 10)
 90                 ball = Ball(event.pos, color, radius, sx, sy)
 91                 balls.append(ball)
 92         refresh(screen, balls)
 93         clock.tick(50)
 94         for ball in balls:
 95             ball.move()
 96             ball.eat(ball)
 97 
 98         pygame.display.flip()
 99 
100     pygame.quit()
101 
102 
103 
104 if __name__ == '__main__':
105     main()
原文地址:https://www.cnblogs.com/charlieyucao/p/8583333.html