python代码解答

5.设计一个Animal(动物)类,包括颜色属性和叫方法。再设计一个Fish(鱼)类,包括尾巴和颜色两个属性,以及叫方法。要求:Fish 类继承自 Animal 类,重写构造方法和叫方法。

class Animal:
    def __init__(self, color):
        self.color = color

    def make_sound(self):
        print("I'm an animal. I make a sound.")

class Fish(Animal):
    def __init__(self, tail, color):
        Animal.__init__(self, color)
        self.tail = tail
        
    def make_sound(self):
        print("I'm a fish. I don't make sound.")

# 创建一个名为“red”的Animal对象
my_animal = Animal("red")

# 输出动物颜色
print("My animal's color is", my_animal.color)

# Animal makes sound
my_animal.make_sound()

# 创建一个名为“blue”的Fish对象,有“fish_tail”属性
my_fish = Fish("fish_tail", "blue")

# 输出鱼的颜色和尾巴属性
print("My fish's color is", my_fish.color)
print("My fish's tail is", my_fish.tail)

# Fish makes sound
my_fish.make_sound()

class Animal:
    def __init__(self):
        self.color = 'black'

    def call(self):
        print('I am an animal. I am', self.color)


class Fish(Animal):
    def __init__(self):
        super().__init__()
        self.color = 'red'

    def call(self):
        print('I am a fish. I am', self.color)


if __name__ == '__main__':
    f = Fish()
    f.call()
# Animal类
class Animal:
    def __init__(self, color):
        self.color = color

    def make_sound(self):
        print("Animal is making a sound.")

# Fish类,继承自Animal类
class Fish(Animal):
    def __init__(self, color, tail):
        super().__init__(color)    # 调用父类构造方法初始化颜色属性
        self.tail = tail           # 初始化尾巴属性

    def make_sound(self):
        print("Fish is making a sound.")