源代码如下:
import random as r
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
self.x -= 1
print('鱼类的位置是:', self.x, self.y)
class Godfish(Fish):
def move(self):
self.x -= 1
print('鲸鱼的位置是:', self.x, self.y)
class Carpfish(Fish):
def move(self):
self.x -= 1
print('鲤鱼的位置是:', self.x, self.y)
class Salmonfish(Fish):
def move(self):
self.x -= 1
print('三文鱼的位置是:', self.x, self.y)
class Shark(Fish):
'''
def __init__(self): # 鲨鱼改写了父类中的 __init__(self) 方法,所以不能移动
self.hungry = True
'''
# 调用未绑定的父类方法
def __init__(self):
# Fish.__init__(self)
super().__init__()
self.hungry = True
def move(self):
self.x -= 1
print('鲨鱼的位置是:', self.x, self.y)
def eat(self):
if self.hungry:
print('鲨鱼就是天天有的吃')
self.hungry = False
else:
print('饱了饱了')
fish = Fish()
fish.move()
goldfish = Godfish()
goldfish.move()
shark = Shark()
shark.eat()
# shark.move() # 会报错,因为方法被子类改写
'''
解决方法有两种:
1、调用未绑定的父类方法
Fish.__init__(self)
2、使用super函数
super().__init__()
'''
shark.move()
# 多重继承形式 class 子类名(父类1, 父类2, 父类3): ...
# 要尽量少使用多重继承,避免出现不可预见的错误
运行结果如下:
鱼类的位置是: 9 8
鲸鱼的位置是: 3 5
鲨鱼就是天天有的吃
鲨鱼的位置是: -1 2