类和对象——面向对象编程
来源:互联网 发布:python jenkins api 编辑:程序博客网 时间:2024/06/14 02:32
学习笔记 :
0.按照以下要求定义一个游乐园门票的类,并计算2个大人+1个小孩平日票价。
·平日票价100元
·周末票价为平日的120%
·儿童半票
参考答案:
我的代码:
>>> class Tickets(): def __init__(self,weekend = False,child = False): self.original = 100 if weekend: self.kd = 1.2 else: self.kd = 1 if child: self.kc = 0.5 else: self.kc = 1 def price(self): return self.original*self.kd*self.kc>>> adult = Tickets()>>> child = Tickets(child = True)>>> total = adult.price()*2 + child.price()>>> print("2个大人+1个小孩的平日票价是%d元"%total)2个大人+1个小孩的平日票价是250元
自己打的代码:
# -*- coding: gbk -*-import random as rclass Turtle: def __init__(self): #初始体力值 self.strength = 100 #随机坐标 self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): nx = self.x + r.choice([1,2,-1,-2]) ny = self.y + r.choice([1,2,-1,-2]) #检查是否超出了X的边界 if nx < 0: self.x = - nx #超出部分为0-nx,改为向右移动 elif nx >10: self.x = 10 - (nx - 10) #超出部分为(nx - 10),改为向左移动 else: self.x = nx #检查是否超出了Y的边界 if ny < 0: self.y = - ny #超出部分为0-ny,改为向右移动 elif ny >10: self.y = 10 - (ny - 10) #超出部分为(ny - 10),改为向左移动 else: self.y = ny #更新体力消耗 self.strength -= 1 return (self.x , self.y) def bite(self): self.strength += 20 if self.strength > 100 : self.strength = 100class Fish: def __init__(self): #随机坐标 self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): nx = self.x + r.choice([1,-1]) ny = self.y + r.choice([1,-1]) #检查是否超出了X的边界 if nx < 0: self.x = - nx #超出部分为0-nx,改为向右移动 elif nx >10: self.x = 10 - (nx - 10) #超出部分为(nx - 10),改为向左移动 else: self.x = nx #检查是否超出了Y的边界 if ny < 0: self.y = - ny #超出部分为0-ny,改为向右移动 elif ny >10: self.y = 10 - (ny - 10) #超出部分为(ny - 10),改为向左移动 else: self.y = ny return (self.x , self.y) turtle = Turtle()fish = []num = 10for i in range(num): f = Fish() fish.append(f)while True: if not len(fish): print("鱼儿没了,游戏结束!") break if not turtle.strength : print("乌龟没力气了,游戏结束!") break turtle_pos = turtle.move() for each in fish[:]: fish_pos = each.move() if fish_pos == turtle_pos: turtle.bite() print("又吃了一条鱼!") fish.remove(each) '''可以这么理解: >>> fish = [1,2,3] >>> fish1 = fish[:] >>> fish1[1] = 0 #将迭代器里第2条改变状态(移动) >>> fish.remove(fish[1]) #将原列表里对应的第2条删除 >>> fish # [1, 3] '''
阅读全文