MST

星途 面试题库

面试题:Python面向对象编程中if语句在多态与异常处理中的应用

假设有一个抽象基类`Animal`,包含抽象方法`make_sound`。有`Dog`、`Cat`、`Bird`三个子类继承自`Animal`并实现`make_sound`方法。在一个`SoundMaker`类中,有一个`play_sound`方法,该方法接受一个`Animal`类型的对象作为参数。请在`play_sound`方法中使用`if`语句来处理可能传入的`None`值(引发自定义异常`InvalidAnimalError`),同时展示如何利用`if`语句结合多态特性来正确调用不同动物的`make_sound`方法。请给出完整代码实现及异常类定义。
11.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
class InvalidAnimalError(Exception):
    pass


class Animal:
    def make_sound(self):
        raise NotImplementedError


class Dog(Animal):
    def make_sound(self):
        return "Woof!"


class Cat(Animal):
    def make_sound(self):
        return "Meow!"


class Bird(Animal):
    def make_sound(self):
        return "Tweet!"


class SoundMaker:
    def play_sound(self, animal):
        if animal is None:
            raise InvalidAnimalError("Animal cannot be None")
        if isinstance(animal, Dog):
            return animal.make_sound()
        elif isinstance(animal, Cat):
            return animal.make_sound()
        elif isinstance(animal, Bird):
            return animal.make_sound()
        else:
            raise ValueError("Unsupported animal type")


# 测试代码
sound_maker = SoundMaker()
dog = Dog()
cat = Cat()
bird = Bird()

try:
    print(sound_maker.play_sound(dog))
    print(sound_maker.play_sound(cat))
    print(sound_maker.play_sound(bird))
    print(sound_maker.play_sound(None))
except InvalidAnimalError as e:
    print(f"Error: {e}")
except ValueError as e:
    print(f"Error: {e}")