函數面向對象編程及文件的讀取

函數node

'''python

名字json

參數/默認值/可變參數-可變參數容許傳入0個或任意個參數,這些可變參數在函數調用時自動組裝爲一個元組api

命名關鍵字參數-關鍵字參數容許傳入0個或任意個含參數名的參數,這些關鍵字參數在函數的內部自動組裝成爲一個字典。緩存

返回值閉包

嵌套定義app

高階函數-Lambda函數(匿名函數)/閉包/偏函數/柯里化dom

Lambda 函數例子:ide

 

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()
相關文章
相關標籤/搜索