Python 【类的多态】
一.多态
#类的多态
class Animal(object): #Animal类继承object
def __init__(self,color):
self.color = color
def eat(self):
print("动物在吃!")
def run(self):
print("动物在跑")
class Cat(Animal): #Cat继承Aninal 继承[属性和方法]
def eat(self): #方法重名
print("猫仔!")
class Dog(Animal): #继承时候,方法重名用子方法
def __init__(self,name,age,color):
super(Dog,self).__init__(color) #super表示父类,调用父类的初始化方法
self.name = name
self.age = age
def eat(self): #方法重名
print("狗仔!")
#多态
def feed(obj):
obj.eat()
#对象作为参数传入
an = Animal("黄")
cat = Cat("橘黄")
dog = Dog("小黑",12,"黑色")
feed(an)
feed(cat)
feed(dog)上面有三种类,Animal类、Cat类、Dog类,三种类中都有共同的方法eat()
使用方法
def feed(obj):
obj.eat()将对象当参数传入,对应的所有方法执行
相关推荐
fly00love 2020-03-08
wangqing 2020-02-13
zhouhaihua00 2020-01-01
jacktangj 2020-01-01
JakobHu 2019-12-21
pangrui0 2019-04-12
HongKongPython 2020-05-12
宿舍 2020-05-06
llwang0 2020-02-29
lynjay 2020-06-06
jameszgw 2020-06-03
Greatemperor 2020-05-17
Darklovy 2020-04-29
austindev 2020-04-25
sunnyJam 2020-04-15
TreasureZ 2020-02-22
jacktangj 2020-02-19
明天你好 2020-02-18