Python面向对象之继承

搬运B站小甲鱼的…

直接贴代码了哦

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("My position is:",self.x,self.y)
class Goldfish(Fish):
    pass
class Carp(Fish):
    pass
class Salmon(Fish):
    pass
class Shark(Fish):
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry:
            print("The dream of a foodie is having food to eat everyday:)")
            self.hungry=False
        else:
            print("Too hungry,I can't eat anymore!")
fish=Fish()
fish.move()
fish.move()
goldfish=Goldfish()
goldfish.move()
goldfish.move()
shark=Shark()
shark.eat()

结果如下:

My position is: 1 1
My position is: 0 1
My position is: 1 1
My position is: 0 1
The dream of a foodie is having food to eat everyday:)

但是运行以下代码时

shark.move()

会有报错

Traceback (most recent call last):
  File "c:/Users/DELL/Desktop/Untitled-1.py", line 32, in <module>
    shark.move()
  File "c:/Users/DELL/Desktop/Untitled-1.py", line 7, in move
    self.x-=1
AttributeError: 'Shark' object has no attribute 'x'

这是因为子类重启父类方法,会把父类方法覆盖掉,所以说’Shark’ object has no attribute ‘x’
解决方案:

def __init__(self):
    super().__init__() 
    self.hungry=True

直接写 super().需要的父类函数
就可以正常运行代码了!

多重继承一般不要使用,会造成混乱

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值