搬运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().需要的父类函数
就可以正常运行代码了!
多重继承一般不要使用,会造成混乱