任务: 用鸟类创造一个等级制度。实现四个类:
类 Bird 具有属性 name 和方法 fly 和 walk。
FlyingBird 类,具有属性 name、ration,并具有相同的方法。配给必须有一个默认值。实现方法eat,它将描述其典型的配给量。
NonFlyingBird 类具有相同的特征,但显然没有属性 fly。添加相同的“吃”方法,但使用有关游泳鸟口味的其他实现。
SuperBird 类,它可以做到所有这些:行走、飞翔、游泳和吃。但要小心你继承的是哪种“吃”方法。 为每个类实现一个 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 类,我正在尝试解析 NonFlyingBirds 的 Fly() 方法。目前 - 它什么也不返回
类的命名非常混乱。为什么你会调用一个类
FlyingBird
但它不添加 fly 功能而是添加 eat 功能?
我会尝试在这个 python 伪代码中清除它。
class Bird:
def eat()
def walk()
class FlyingBird(Bird):
def fly()
class NonFlyingBird(Bird):
def swim()
这个设计更干净,更好地展示了每个
class
的意图和提供的功能。
对于
SuperBird
来说,它可以做所有事情,在python
中,您可以使用多重继承的概念。
class SuperBird(FlyingBird, NonFlyingBird):
# init call etc ...
使用多重继承,你需要小心不要遇到钻石问题,但据我所知,这不应该是
python
中的问题,因为它正确地使用了多重继承并且具有鸭子类型更多内容就在这里。
您可以在
NonFlyingBird
类中引发 AttributeError,如下所示:
def fly(self):
raise AttributeError(f"'{self.name}' object has no attribute 'fly'")