目前在自学python,我是刚入门的,如何进行这个循环呢,求改善
各子类把构造方法可以稍微修改下,把a的数据类型改为列表,然后在里面新建各个动物的对象即可。
修改如下:
参考链接:
# 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()
```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()
```