千峰笔记-多继承与多态

 

 

多继承

 

多继承实现

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)

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值