2024 桐庐半程马拉松
00:00:00
时间
0.00
距离(公里)
--:--
配速
--
步频
--
心率 (bpm)
--
配速
步频
|
share-image
ESC

python 的继承和多态

python 由于是面向对象的语言,因此都有继承和多态的特点

继承

class Animal(object):

def run(self):
print('Animal is running....')



class Dog(Animal):
pass

class Cat(Animal):
pass


dog = Dog()
dog.run()

cat = Cat()
cat.run()


我们看到上面的 Dog 和 Cat 都继承了 Animal,python 中继承是在 class 的类名的括号中加入父类的名称。

输出

Animal is running....
Animal is running....

但是我们看上面的输出肯定不是我们想要的,我们希望 dog 输入 dog is running cat 输出 cat is running。

我们修改下代码

class Animal(object):

def run(self):
print('Animal is running....')



class Dog(Animal):

def run(self):
print("Dog is running....")

class Cat(Animal):

def run(self):
print("Cat is running....")


dog = Dog()
dog.run()

cat = Cat()
cat.run()


子类重写了父类的 run 方法,这就叫多态

在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行:

文章作者:阿文
文章链接: https://www.awen.me/post/17678.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客
本文于 2018-04-16 发布,已超过半年(2845天),请注意甄别内容是否已过期。