Python第三周习题集(一) (工资结算系统 抽象类 静态方法 贪吃蛇 分数的重写 五子棋 大球吃小球 )...
生活随笔
收集整理的這篇文章主要介紹了
Python第三周习题集(一) (工资结算系统 抽象类 静态方法 贪吃蛇 分数的重写 五子棋 大球吃小球 )...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 工資結算系統 1. 部門經理 1.5萬元/月 2. 程序員 工作時間 150元/小時 3.銷售員 1200底薪,+ %5銷售額的提成
# 給你員工,得出工資。 員工類,父類 下面3類子類。
#我寫的
class Staff(object):def __init__(self, name, age):self._name = nameself._age = age@propertydef name(self):return self._name@propertydef age(self):return self._ageclass Department_manager(Staff):def __init__(self, name, age, salary):super().__init__(name, age)self._salary = salary@propertydef salary(self):return self._salarydef get_money(self):print('%s歲的%s工作了一個月掙了%s' % (self._age, self._name, self._salary))class Programer(Staff):def __init__(self, name, age, salary):super().__init__(name, age)self._salary = salary@propertydef salary(self):return self._salarydef get_money(self, time):print('%s歲的%s工作了一個月共%s小時掙了%s' % (self._age, self._name, time, self._salary * time))class Salesman(Staff):def __init__(self, name, age, sale):super().__init__(name, age)self._sale = sale@propertydef salary(self):return self._saledef get_money(self):salary = self._sale * 5 / 100 + 1200print('銷售員%s一個月掙了%s' % (self._name, salary))def main():which = str(input('請輸入員工類型:部門經理/程序員/銷售員'))if which == '部門經理':name = input('請輸入名字')age = input('請輸入年齡')man1 = Department_manager(name, age, '1.5萬元')print(man1.get_money())elif which == '程序員':name = input('請輸入名字')age = input('請輸入年齡')man2 = Programer(name, age, 150)time = int(input('請輸入工作了多少小時'))print(man2.get_money(time))elif which == '銷售員':name = input('請輸入名字')age = input('請輸入年齡')sale = int(input('請輸入銷售額'))man3 = Salesman(name, age, sale)print(man3.get_money())if __name__ == '__main__':main()
#我寫的
class Staff(object):def __init__(self, name, age):self._name = nameself._age = age@propertydef name(self):return self._name@propertydef age(self):return self._ageclass Department_manager(Staff):def __init__(self, name, age, salary):super().__init__(name, age)self._salary = salary@propertydef salary(self):return self._salarydef get_money(self):print('%s歲的%s工作了一個月掙了%s' % (self._age, self._name, self._salary))class Programer(Staff):def __init__(self, name, age, salary):super().__init__(name, age)self._salary = salary@propertydef salary(self):return self._salarydef get_money(self, time):print('%s歲的%s工作了一個月共%s小時掙了%s' % (self._age, self._name, time, self._salary * time))class Salesman(Staff):def __init__(self, name, age, sale):super().__init__(name, age)self._sale = sale@propertydef salary(self):return self._saledef get_money(self):salary = self._sale * 5 / 100 + 1200print('銷售員%s一個月掙了%s' % (self._name, salary))def main():which = str(input('請輸入員工類型:部門經理/程序員/銷售員'))if which == '部門經理':name = input('請輸入名字')age = input('請輸入年齡')man1 = Department_manager(name, age, '1.5萬元')print(man1.get_money())elif which == '程序員':name = input('請輸入名字')age = input('請輸入年齡')man2 = Programer(name, age, 150)time = int(input('請輸入工作了多少小時'))print(man2.get_money(time))elif which == '銷售員':name = input('請輸入名字')age = input('請輸入年齡')sale = int(input('請輸入銷售額'))man3 = Salesman(name, age, sale)print(man3.get_money())if __name__ == '__main__':main()
?抽象類
Python沒有從語言層面支持抽象類的概念,我們可以從abc模塊來制造抽象類的效果。
在定義類的時候,通過指定metaclass=ABCMeta可以將類聲明為抽象類
抽象類是不能創建對象的,抽象類只是拿來被繼承的,給其他類繼承
abc模塊中還有一個叫abstractmethon,通過這個包裝器,可以將方法包裝為抽象方法,必須要求子類重寫。
rom abc import ABCMeta, abstractmethodclass Employee(object, metaclass=ABCMeta):"""員工"""def __init__(self, name, age):"""初始化方法"""self._name = nameself._age = age@propertydef name(self):return self._name@propertydef age(self):return self._age@abstractmethod # 變型為抽象類,以下的子類繼承這個的時候,必須重寫這個方法。def get_salary(self):"""計算月薪"""passclass Manager(Employee):def __init__(self, name, age):super().__init__(name, age)def get_salary(self):return 15000class Programer(Employee):def __init__(self, name, age):super().__init__(name, age)self._working_hour = 0@propertydef working_hour(self):return self._working_hour# 非必要屬性,通過setter方法給出,必要屬性,通過屬性給出,不輕易修改 @working_hour.setterdef working_hour(self, working_hour):self._working_hour = working_hour if working_hour > 0 else 0def get_salary(self):return self._working_hour * 150class Salesman(Employee):def __init__(self, name, age):super().__init__(name, age)self._sales = 0@propertydef sales(self):return self._sales@sales.setterdef sales(self, sales):self._sales = sales if sales > 0 else 0def get_salary(self):return 1200 + self._sales * 5 / 100def main():emps = [Manager('曹宇', 22), Programer('楊茜然', 22),Manager('張超', 22), Programer('李西北', 22),Salesman('劉家咯', 22)]for emp in emps:# 識別類型,很重要*******if isinstance(emp, Programer):emp.working_hour = int(input('請輸入%s本月工作時間:' % emp.name))elif isinstance(emp, Salesman):emp.sales = int(input('請輸入%s本月銷售額:' % emp.name))# 同樣是接受get_salary這個消息,但是不用員工表現出了不同行為# 因為三個子類都重寫了這個方法,所以這個方法會表現出多態行為print('%s本月工資為:¥%.2f元' % (emp.name, emp.get_salary()))if __name__ == '__main__':main()靜態方法
是用來發給這個類的爸爸的,不是發給這個類的。有兩種方法。
1.@staticmethon
2.@classmethon 下面這個比上面這個多了一個參數,(cls)
from math import sqrtclass Triangle(object):def __init__(self, a, b, c):self._a = aself._b = bself._c = c# 靜態方法, 用以發給類,不是發給對象的。就是發給它爸爸的。# @staticmethod # @classmethod 也是發給類的,區別,# def is_valid(a, b, c):# return a + b > c and a + c > b and b + c > a @classmethod # @classmethod 也是發給類的,區別,def is_valid(cls, a, b, c):return a + b > c and a + c > b and b + c > a@propertydef perimeter(self):return self._a + self._b + self._c@propertydef area(self):half = self.perimeter / 2return sqrt(half * (half - self._a) * (half - self._b) * (half - self._c))def main():a = b = c = 1if Triangle.is_valid(a, b, c): # 靜態方法。t = Triangle(a, b, c)print(t.perimeter) # 對象來執行# 或者用 (Triangle.perimeter(t)) 類來執行,傳入參數。print(t.area)else:print('無法構成三角形!')if __name__ == '__main__':main()?貪吃蛇
import pygame from random import randint from abc import ABCMeta, abstractmethodBLACK_COLOR = (0, 0, 0) FOOD_COLOR = (236, 111, 187) GREEN_COLOR = (0, 255, 0)UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3class GameObject(object, metaclass=ABCMeta):def __init__(self, x=0, y=0, color=BLACK_COLOR):self._x = xself._y = yself._color = color@propertydef x(self):return self._x@propertydef y(self):return self._y@propertydef color(self):return self._color@abstractmethod # 后面繼承的子類都必須重寫此方法,不然報錯def draw(self, screen):passclass SnakeNode(GameObject): # 蛇節def __init__(self, x, y, size, color=GREEN_COLOR):"""x y 為坐標,size為寬高。:param x::param y::param size::param color:"""super(SnakeNode, self).__init__(x, y, color)self._size = size@propertydef size(self):return self._sizedef draw(self, screen):"""畫蛇的節點,其中,位置,由左上的位置坐標和寬高組成。0,表示實心。:param screen::return:"""pygame.draw.rect(screen, self._color, [self._x, self._y, self._size, self._size], 0)pygame.draw.rect(screen, BLACK_COLOR, [self._x, self._y, self._size, self._size], 1)class Snake(GameObject):def __init__(self):"""由蛇節組成?"""super(Snake, self).__init__()self._dir = LEFTself._nodes = []self._alive = Truefor index in range(5):node = SnakeNode(290 + index * 20, 250, 20)self._nodes.append(node)@propertydef head(self):return self._nodes[0]@propertydef dir(self):return self._dir@propertydef alive(self):return self._alivedef collide(self, wall):"""撞到墻返回真,否則返回False"""head = self.headif head.x < wall.x or head.x + head.size > wall.x + wall.width\or head.y < wall.y or head.y + head.size > wall.y + wall.height:self._alive = Falsedef eat_food(self, food):if self.head.x == food.x and self.head.y == food.y:tail = self._nodes[-1]self._nodes.append(tail)return Truereturn Falsedef draw(self, screen):for node in self._nodes:node.draw(screen)def move(self):if self._alive:snake_dir = self._dirx, y, size = self.head.x, self.head.y, self.head.sizeif snake_dir == UP:y -= sizeelif snake_dir == RIGHT:x += sizeelif snake_dir == DOWN:y += sizeelse:x -= sizenew_head = SnakeNode(x, y, size)self._nodes.insert(0, new_head)self._nodes.pop()def change_dir(self, new_dir):if (self._dir + new_dir) % 2 != 0:self._dir = new_dirclass Wall(GameObject):def __init__(self, x, y, width, height, color=BLACK_COLOR):super(Wall, self).__init__(x, y, color)self._width = widthself._height = height@propertydef width(self):return self._width@propertydef height(self):return self._heightdef draw(self, screen):pygame.draw.rect(screen, self._color, [self._x, self._y, self._width, self._height], 5)class Food(GameObject):def __init__(self, x, y, size, color=FOOD_COLOR):super(Food, self).__init__(x, y, color)self._size = sizeself._hidden = Falsedef draw(self, screen):"""讓食物閃爍起來"""if not self._hidden:pygame.draw.circle(screen, self._color,(self._x + self._size // 2, self._y + self._size // 2),self._size // 2, 0)self._hidden = not self._hiddendef main():def refresh():"""刷新游戲窗口"""screen.fill([242, 242, 242])snake.draw(screen)wall.draw(screen)food.draw(screen)pygame.display.flip()def handle_key_event(key_event):"""接受按鍵事件"""key = key_event.keyif key == pygame.K_F2:reset_game()else:if snake.alive:new_dir = snake.dirif key == pygame.K_w:new_dir = UPelif key == pygame.K_d:new_dir = RIGHTelif key == pygame.K_s:new_dir = DOWNelif key == pygame.K_a:new_dir = LEFTif new_dir != snake.dir:snake.change_dir(new_dir)def create_food():row = randint(0, 29)col = randint(0, 29)return Food(10 + 20 * row, 10 + 20 * col, 20)def reset_game():nonlocal food, snakefood = create_food()snake = Snake()wall = Wall(10, 10, 600, 600)food = create_food()snake = Snake()pygame.init()pygame.display.set_caption('貪吃蛇')screen = pygame.display.set_mode([620, 620]) # 左上角是坐標原點。screen.fill([242, 242, 242])pygame.display.flip()clock = pygame.time.Clock() # 幀數,游戲每秒的刷新次數。幀數越高越好,但是要機器能跟上。running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:handle_key_event(event) # 調用按鍵函數if snake.alive:refresh() # 調用刷新函數clock.tick(10) # 刷新次數if snake.alive:snake.move()snake.collide(wall)if snake.eat_food(food):food = create_food()pygame.quit()if __name__ == '__main__':main()分子分母的重寫
from math import gcdclass Fraction(object):def __init__(self, num=1, den=1): # 后面跟兩個下劃線,是共有的,如果后面有一個或沒有,才是私有的。"""分子分母:param num:分子:param den: 分母"""if den == 0:raise ValueError('分母不能為零') # 你敢讓他為零,我就死給你看self._num = numself._den = denself.normalize() # 自動調用正?;?/span>self.simplify() # 自動調用化簡 @propertydef num(self):return self._num# @num.setter# def num(self, num):# self._num = num @propertydef den(self):return self._den# @den.setter# def den(self, den):# self._den = dendef add(self, other):"""加法"""return Fraction(self._num * other.den + self._den * other.num,self._den * other.den)def __add__(self, other):"""運算符重載/重寫"""return self.add(other)def sub(self, other):"""減法"""return Fraction(self._num * other.den - self._den * other.num,self._den * other.den)def __sub__(self, other):return self.sub(other)def mul(self, other):"""乘法"""return Fraction(self._num * other.num ,self._den * other.den)def __mul__(self, other):return self.mul(other)def truediv(self, other):"""除法"""return Fraction(self._num * other.den ,self._den * other.num)def __truediv__(self, other):return self.truediv(other)def simplify(self):"""化簡:return:"""if self._num != 0 and self._den != 1:factor = gcd(abs(self._num), abs(self._den))if factor > 1:self._den //= factorself._num //= factordef normalize(self):"""正規化:return:"""if self._den < 0:self._num = -self._numself._den = -self._dendef __str__(self):"""方法的自動調用"""if self._num == 0:return '0'elif self._den == 1:return str(self._num)else:return '%d/%d' % (self._num, self._den)def main():f1 = Fraction(-1, -3)f2 = Fraction(4, 2)f3 = Fraction(0, 4)print(f1 + f2)print(f2 - f1)print(f3 * f1)print(f1 / f2)if __name__ == '__main__':main()五子棋
import pygameEMPTY = 0 BLACK = 1 WHITE = 2black_color = [0, 0, 0] white_color = [255, 255, 255]class RenjuBoard(object):def __init__(self):self._board = [[]] * 15self.reset()def reset(self):"""重置棋盤"""for row in range(len(self._board)):self._board[row] = [EMPTY] * 15def move(self, row, col, is_black):if self._board[row][col] == EMPTY:self._board[row][col] = BLACK if is_black else WHITEreturn Truereturn Falsedef draw(self, screen):"""畫棋盤,天元,四點,畫棋子:param screen::return:"""for i in range(1, 16):pygame.draw.line(screen, black_color, [40, i * 40], [600, i * 40], 1) # 畫行pygame.draw.line(screen, black_color, [i * 40, 40], [i * 40, 600], 1) # 畫列pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 4) # 畫邊框pygame.draw.circle(screen, black_color, [320, 320], 5, 0) # 坐標,半徑,0是實心,1是圓周的粗細pygame.draw.circle(screen, black_color, [160, 160], 5, 0)pygame.draw.circle(screen, black_color, [480, 480], 5, 0)pygame.draw.circle(screen, black_color, [160, 480], 5, 0)pygame.draw.circle(screen, black_color, [480, 160], 5, 0)for row in range(len(self._board)):for col in range(len(self._board[row])):if self._board[row][col] != EMPTY: # 對于棋盤上的所有點,如果部位ccolor = black_color if self._board[row][col] == BLACK else white_colorpos = [40 * (col + 1), 40 * (row + 1)]pygame.draw.circle(screen, ccolor, pos, 18, 0)def main():board = RenjuBoard()is_black = Truepygame.init()pygame.display.set_caption('五子棋')screen = pygame.display.set_mode([640, 640])screen.fill([255, 255, 0]) # 紅綠藍三原色的值! board.draw(screen)pygame.display.flip()running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYUP:board.reset()elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:x, y = event.posrow = round((y - 40) / 40)col = round((x - 40) / 40)if board.move(row, col, is_black):is_black = not is_blackscreen.fill([255, 255, 0])board.draw(screen)pygame.display.flip()pygame.quit()if __name__ == '__main__':main()打球吃小球
from random import randint import pygameclass Ball(object):def __init__(self, center, color, radius, sx, sy):self._center = centerself._color = colorself._radius = radiusself._sx = sxself._sy = sy@propertydef center(self):return self._center@propertydef radius(self):return self._radiusdef move(self):"""移動后的坐標"""x, y = self._center[0], self._center[1]x += self._sxy += self._syself._center = (x, y)if (x + self._radius >= 800 and self._sx > 0) or (x - self._radius <= 0 and self._sx < 0):self._sx = -self._sxif (y + self._radius >= 600 and self._sy > 0) or (y - self._radius <= 0 and self._sy < 0):self._sy = - self._sydef eat(self, other):passdef draw(self, screen):"""畫一個圓"""pygame.draw.circle(screen, self._color, self._center,self._radius, 0)def refresh(screen, balls):bg_color = (242, 242, 242)screen.fill(bg_color)for ball in balls:ball.draw(screen)pygame.display.flip()def random_color():red = randint(0, 255)green = randint(0, 255)blue = randint(0, 255)return red, green, bluedef main():pygame.init()balls = []screen = pygame.display.set_mode([800, 600]) # 窗口大小pygame.display.set_caption('大球吃小球') # 標題clock = pygame.time.Clock()running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.MOUSEBUTTONDOWN and \event.button == 1:# = event.poscolor = random_color()radius = randint(10, 100)sx, sy = randint(-10, 10), randint(-10, 10)ball = Ball(event.pos, color, radius, sx, sy)balls.append(ball)refresh(screen, balls)clock.tick(20)for ball in balls:ball.move()pygame.quit()if __name__ == '__main__':main()?
轉載于:https://www.cnblogs.com/zl666/p/8588020.html
總結
以上是生活随笔為你收集整理的Python第三周习题集(一) (工资结算系统 抽象类 静态方法 贪吃蛇 分数的重写 五子棋 大球吃小球 )...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 管理计算机中的文件,管理计算机中的文件.
- 下一篇: CTO教你,如何快速培养下属,让你拥有得