ladysosoli 2020-03-01
#类的多态
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()将对象当参数传入,对应的所有方法执行