首先定义一个父类Animal,注意父类中函数需要一个self,类似于C++中的this,指代创建实例以后的当前对象
class Animal():
def eat(self):
print("eating")
def act(self):
print("move")
然后我们定义其子类:注意这个时候,如果创建Mammal对象,则使用eat是打印Mammal eating,而使用act是使用父类的act函数。
class Mammal(Animal):
def eat(self):
print("Mammal eating")
def breastfeed(self):
print("milk feeding")
随后再定义子类的子类:
class Cat(Mammal):
def __init__(self,age):
self.age = age
def printAge(self):
print(self.age)
def eat(self):
print("eating fish")
注意这个时候,eat同样覆盖了父类的eat函数。
然后我们测试:
Daju = Cat(10)
Daju.eat()
Daju.act()
打印结果:
eating fish
move