请看下面代码,在shark对象调用eat方法时候报错,原因是shark类继承自Fish,但是改写了父类的init,造成继承自父类的x属性找不到了
import random as r
class Fish(object):
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -= 1
print("My Location is (%d,%d)"%(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("My Dream is Eat Everyday...")
self.hungry = False
else:
print("I am Full...")
if __name__ == "__main__":
fish = Fish()
fish.move()
shark = Shark()
shark.eat()
shark.move()
解决方案一:
在子类中调用父类的初始化init函数
解决方案二:Super方法