热线电话:13121318867

登录
2020-11-07 阅读量: 642
老师所说的具有继承性的多态性应该如何理解?

问题详述:老师所说的具有继承性的多态性应该如何理解?


解答:

在Python中,多态性允许我们在子类中定义与父类中的方法具有相同名称的方法。在继承中,子类从父类继承方法。但是,可以修改从父类继承的子类中的方法。在从父类继承的方法不太适合子类的情况下,这尤其有用。在这种情况下,我们在子类中重新实现该方法。在子类中重新实现方法的过程称为 函数重写


class Bird:

def intro(self):

print("There are many types of birds.")


def flight(self):

print("Most of the birds can fly but some cannot.")


class sparrow(Bird):

def flight(self):

print("Sparrows can fly.")


class ostrich(Bird):

def flight(self):

print("Ostriches cannot fly.")


obj_bird = Bird()

obj_spr = sparrow()

obj_ost = ostrich()


obj_bird.intro()

obj_bird.flight()


obj_spr.intro()

obj_spr.flight()


obj_ost.intro()

obj_ost.flight()


Output:

There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.


38.6931
0
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子