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 方法,这就叫多态
在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行:
文章作者:阿文
版权声明:本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自
阿文的博客!