zoukankan      html  css  js  c++  java
  • 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()

    运行结果如下:

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

    对于Dog来说,Animal就是它的父类,对于Animal来说,Dog就是它的子类。CatDog类似。

    继承有什么好处?最大的好处是子类获得了父类的全部功能。由于Animial实现了run()方法,因此,DogCat作为它的子类,什么事也没干,就自动拥有了run()方法:

    -------------------------------------------------------------------------------------------------------

    多太
    class Dog(Animal):
    
        def run(self):
            print('Dog is running...')
    
    class Cat(Animal):
    
        def run(self):
            print('Cat is running...')

    再次运行,结果如下:

    Dog is running...
    Cat is running...

    当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()
    这样,我们就获得了继承的另一个好处:多态。
     
  • 相关阅读:
    集合
    字典
    元组
    列表
    数字类型和字符串类型
    Python 数据类型
    jq的一点点
    常用到jq的ajax
    上传
    下载
  • 原文地址:https://www.cnblogs.com/fkkk/p/9049466.html
Copyright © 2011-2022 走看看