多继承
多继承实现
father.py
class Father(object):
def __init__(self, money):
self.money = money
def play(self):
print("play")
def func(self):
print("func1")
mother.py
class Mother(object):
def __init__(self, faceValue):
self.faceValue = faceValue
def eat(self):
print("eat")
def func(self):
print("func2")
child.py
from father import Father
from mother import Mother
class Child(Father, Mother):
def __init__(self, money, faceValue):
#写法
Father.__init__(self, money)
Mother.__init__(self, faceValue)
self.height = 10
mulinheri.py
from Child import Child
def main():
c = Child(300, 100)
print(c.money, c.faceValue)
c.play()
c.eat()
#父类中方法名相同,默认调用的是在括号中排前面的父类中的方法
c.func()
if __name__ == "__main__":
main()
多态
一种事物的多种形态
最终目标:人可以喂任何一种动物
animal.py
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self):
print(self.name + "吃")
cat.py
from animal import Animal
class Cat(Animal):
def __init__(self, name):
#self.name = name
super(Cat,self).__init__(name)
# def eat(self):
# print(self.name + "吃")
mouse.py
from animal import Animal
class Mouse(Animal):
def __init__(self, name):
#self.name = name
super(Mouse,self).__init__(name)
# def eat(self):
# print(self.name + "吃")
person.py
class Person(object):
def feedCat(self, cat):
print("给食物")
cat.eat()
def feedMouse(self, mouse):
print("给食物")
mouse.eat()
def feedAnimal(self, ani):
print("给食物")
ani.eat()
polymor.py
from cat import Cat
from mouse import Mouse
from person import Person
tom = Cat("Tom")
jerry = Mouse("jerry")
tom.eat()
jerry.eat()
#再添加一百种动物,每种都有name属性和eat方法
#采用继承,定义一个有name属性和eat方法的animal类,让所有的动物都继承自animal
#定义一个人类,可以喂猫和老鼠吃东西
per = Person()
per.feedCat(tom)
per.feedMouse(jerry)
#tom和Jerry都继承自动物
per.feedAnimal(tom)
per.feedAnimal(jerry)