栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python-Fish类的继承

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/657388.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号