python之继承和多态练习题

img

img


目前自学python,想知道如何进行这个循环,又是怎么改善的呢

目前在自学python,我是刚入门的,如何进行这个循环呢,求改善

各子类把构造方法可以稍微修改下,把a的数据类型改为列表,然后在里面新建各个动物的对象即可。

修改如下:

参考链接:


Python入门 class类的继承 - 知乎 面向对象的编程带来的主要好处之一是代码的重用,实现各种重用的方法之一是通过继承机制。继承完全可以理解成类之间的父类和子类型关系。 继承概念:继承是类与类的一种关系,是一种子类与父类的关系,即爸爸与儿… https://zhuanlan.zhihu.com/p/30239694




# https://www.runoob.com/python3/python3-class.html

class Animal:

    def __init__(self,name,weight,height):
        self.name=name
        self.weight=weight
        self.height=height

    def eat(self):
        print(self.name+"在吃!")

    def sour(self):
        print(self.name+"在叫!")


# https://zhuanlan.zhihu.com/p/30239694
class  Cat(Animal):

    def __init__(self,name,weight,height):
        super(Cat,self).__init__(name,weight,height)

    def eat(self):
        print("猫"+self.name+"在吃鱼!")

    def sour(self):
        print("猫"+self.name+"在喵喵!")
        
class  Dog(Animal):

    def __init__(self,name,weight,height):
        super(Dog,self).__init__(name,weight,height)

    def eat(self):
        print("狗"+self.name+"在吃骨头!")

    def sour(self):
        print("狗"+self.name+"在汪汪!")


class  Bird(Animal):

    def __init__(self,name,weight,height):
        super(Bird,self).__init__(name,weight,height)

    def eat(self):
        print("鸟"+self.name+"在吃虫子!")

    def sour(self):
        print("鸟"+self.name+"在啾啾!")

a=[Cat("灰灰",20,10),Dog("阿虎",60,30),Bird("花花",1,6)]
for i in a:
    i.eat()
    i.sour()
    print()




img



```python
class Animal:

    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height

    def talk(self):
        print('动物说话')

    def eat(self):
        print('动物吃东西')


class Dog(Animal):

    def talk(self):
        print(self.name+'汪汪汪')

    def eat(self):
        print(self.name+'吃肉')


class Cat(Animal):

    def talk(self):
        print(self.name+'喵~')

    def eat(self):
        print(self.name+'吃鱼')


class Bird(Animal):

    def talk(self):
        print(self.name+'吱吱~')

    def eat(self):
        print(self.name+'吃虫')


dog1 = Dog('Tom', 10, 10)
dog2 = Dog('Tom', 25, 30)
dog3 = Dog('Tom', 15, 30)

cat1 = Cat('TomCat', 11, 22)

bird=Bird('angry bird',1,2)

animals = [dog1, cat1,bird]

for a in animals:
    a.eat()
    a.talk()

```