You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重写继承的方法以抛出指定的AttributeError?

任务

创建鸟类的类层次结构,实现四个类:

  • 类 Bird,包含属性 name,以及方法 fly 和 walk。
  • 类 FlyingBird,包含属性 name、ration(需设置默认值),并拥有与Bird相同的方法。实现方法 eat,用于描述其典型的食物。
  • 类 NonFlyingBird,具备相同的特征,但显然没有 fly 方法。添加相同的eat方法,但针对游禽的食性做不同实现。
  • 类 SuperBird,具备全部功能:walk、fly、swim 和 eat,注意要选择正确的eat方法进行继承。
    为每个类实现 str() 方法。

示例

>>> b = Bird("Any")
>>> b.walk()
"Any bird can walk"

p = NonFlyingBird("Penguin", "fish")
>>> p.swim()
"Penguin bird can swim"
>>> p.fly()
AttributeError: 'Penguin' object has no attribute 'fly'
>>> p.eat()
"It eats mostly fish"

c = FlyingBird("Canary")
>>> str(c)
"Canary bird can walk and fly"
>>> c.eat()
"It eats mostly grains"

s = SuperBird("Gull")
>>> str(s)
"Gull bird can walk, swim and fly"
>>> s.eat()
"It eats mostly fish"

我的代码

class Bird:
    def __init__(self, name):
        self.name = name

    def fly(self):
        return f'{self.name} bird can fly'

    def walk(self):
        return f'{self.name} bird can walk'

    def __str__(self):
        return f'{self.name} bird can walk and fly'


class FlyingBird(Bird):
    def __init__(self, name, ration='grains'):
        super().__init__(name)
        self.ration = ration

    def eat(self):
        return f'It eats mostly {self.ration}'

    def __str__(self):
        return f'{self.name} bird can walk and fly'


class NonFlyingBird(Bird):
    def __init__(self, name, ration='fish'):
        super().__init__(name)
        self.ration = ration

    def swim(self):
        return f'{self.name} bird can swim'

    def fly(self):
        try:
            raise AttributeError
        except AttributeError as e:
            return e

    def eat(self):
        return f'It eats mostly {self.ration}'

    def __str__(self):
        return f'{self.name} bird can walk and fly'


class SuperBird:
    pass

当前问题

我还未开始编写SuperBird类,目前正在解决NonFlyingBird的fly()方法问题,当前该方法无法正确抛出错误,而是返回异常对象。

更新

我已经解决了该任务,谢谢!

内容的提问来源于stack exchange,提问作者user24032725

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 21:13:18