0、多态特征
1、定义一个新类继承已有的这个类
2、类似C++中的this指针,可以认为self其实就是实例对象的唯一标志
3、在属性或方法名字前加上双下划线,变成私有,这样从外部无法直接访问到
4、__init__方法在类实例化时被自动调用,称之为魔法方法,可以重写这个方法,为对象建立初始化方案
5、一个类(类对象)可以实例化出无数的对象(实例对象)Python为了区分是哪个实例对象调用了方法,于是要求方法必须绑定(通过self参数)才能调用,而未实例化的类对象直接调用方法,因缺少self参数,所以会报错
0、
class ticket():
common_ticket = 100
sunday_common_ticket = common_ticket * 1.2
child_ticket = common_ticket * 0.5
sunday_child_ticket = child_ticket * 0.5
def cal_ticket(self):
return self.common_ticket * 2 + self.child_ticket
运行结果
>>> a = ticket()
>>> a.cal_ticket()
250.0
1、
import random
x_min = 0
x_max = 10
y_min = 0
y_max = 10
class tortoise():
energe = 100
t_x = random.randint(0,10)
t_y = random.randint(0,10)
t_direction = random.randint(1,4)#用4个数字代表四个方向
t_path = random.randint(1,2)
def set_t_direction(self):
self.t_direction = random.randint(1,4)
def set_t_path(self):
self.t_path = random.randint(1,2)
class fish():
f_x = random.randint(0,10)
f_y = random.randint(0,10)
f_direction = random.randint(1,4)
f_path = 1
def set_f_direction(self):
self.f_direction = random.randint(1,4)
tortoise1 = tortoise()
fish_list = list()
for i in range(10):
fish_list.append( fish())
def t_move(tortoise):
tortoise.set_t_direction()
tortoise.set_t_path()
if tortoise.t_direction == 1:
tortoise.t_y += tortoise.t_path
if tortoise.t_direction == 3:
tortoise.t_y -= tortoise.t_path
if tortoise.t_direction == 2:
tortoise.t_x -= tortoise.t_path
if tortoise.t_direction == 4:
tortoise.t_x += tortoise.t_path
if tortoise.t_x < x_min:
tortoise.t_x = 2 * x_min - tortoise.t_x
if tortoise.t_x > x_max:
tortoise.t_x = 2 * x_max - tortoise.t_x
if tortoise.t_y < y_min:
tortoise.t_y = 2 * y_min - tortoise.t_y
if tortoise.t_y > y_max:
tortoise.t_y = 2 * y_max - tortoise.t_y
tortoise.energe -= 1
def f_move(fish):
fish.set_f_direction()
if fish.f_direction == 1:
fish.f_y += 1
if fish.f_direction == 3:
fish.f_y -= 1
if fish.f_direction == 2:
fish.f_x -= 1
if fish.f_direction == 4:
fish.f_x += 1
if fish.f_x < x_min:
fish.f_x = 2 * x_min - fish.f_x
if fish.f_x > x_max:
fish.f_x = 2 * x_max - fish.f_x
if fish.f_y < y_min:
fish.f_y = 2 * y_min - fish.f_y
if fish.f_y > y_max:
fish.f_y = 2 * y_max - fish.f_y
len1 = 10
while True:
t_move(tortoise1)
if tortoise1.energe == 0:
print('乌龟体力耗尽')
break
len1 = len(fish_list)
if len1 == 0:
print('鱼儿被吃光了')
break
for i in range(len1):
f_move(fish_list[i])
for each_fish in fish_list:
if each_fish.f_x == tortoise1.t_x and each_fish.f_y == tortoise1.t_y:
fish_list.remove(each_fish)
print('一条鱼儿被吃掉')
tortoise1.energe += 20
if tortoise1.energe >100:
tortoise1.energe = 100
print('游戏结束')
运行结果
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
一条鱼儿被吃掉
乌龟体力耗尽
游戏结束