Python-Fish类的继承

源代码如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值