python多态_python 多态

第一类多态:

from cat import Cat

from mouse import Mouse

from person import Person

'''

多态:一种事物的多种形态

最终目标:人可以喂任何一种动物

'''

tom = Cat("tom")

jerry = Mouse("jerry")

tom.eat()

jerry.eat()

#思考:在添加100种动物,也都有name属性和eat方法

#定义了一个有name属性和eat方法的Animal类,让所有的动物类都继承自Animal

#定义一个人类,可以喂猫和老鼠吃东西

per = Person()

#per.feedCat(tom)

#per.feedMouse(jerry)

#思考:人要喂100种动物,难道要写100个feed方法吗??

#tom和jerry都继承自动物

per.feedAnimal(tom)

per.feedAnimal(jerry)

第二类cat:

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:

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 + "吃")

第四类animal:

class Animal(object):

def __init__(self, name):

self.name = name

def eat(self):

print(self.name + "吃")

第五类person:

class Person(object):

'''

def feedCat(self, cat):

print("给你食物")

cat.eat()

def feedMouse(self, mouse):

print("给你食物")

mouse.eat()

'''

def feedAnimal(self, ani):

print("给你食物")

ani.eat()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值